在 Java 中解析 XML 文件可以使用多个库,其中最常用的是 javax.xml.parsers
包以及第三方库,如 DOM4J
和 JDOM
。这里将介绍如何使用标准库 javax.xml.parsers
和 XPath
来实现解析 XML 中某个节点下具有相同值的情况。
准备 XML 文件
首先,需要准备一个 XML 文件,假设其内容如下:
xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>Java Programming</title>
<author>John Doe</author>
</book>
<book>
<title>Python Programming</title>
<author>Jane Smith</author>
</book>
<book>
<title>Java Programming</title>
<author>Emily White</author>
</book>
</books>
Java 代码
使用 javax.xml.parsers
包和 XPath
的示例代码如下:
java
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class XMLParser {
public static void main(String[] args) {
try {
// 加载 XML 文件
File inputFile = new File("books.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
// 创建 XPath 工具
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
// 查找具有相同标题的 book 节点
String titleToSearch = "Java Programming";
String expression = String.format("/books/book[title='%s']", titleToSearch);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
// 遍历结果并打印相关信息
List<String> authors = new ArrayList<>();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String author = element.getElementsByTagName("author").item(0).getTextContent();
authors.add(author);
}
}
// 输出结果
System.out.printf("Books with the title '%s':%n", titleToSearch);
for (String author : authors) {
System.out.println("Author: " + author);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
代码详细说明
- 解析器设置:使用
DocumentBuilderFactory
创建一个DocumentBuilder
,将 XML 文件加载为Document
对象,供后续查询使用。 - XPath:
XPath
提供了强大的 XML 查询语法,类似于数据库查询。在这里,我们使用它查找特定的title
值。 - 表达式:
XPath
表达式类似于文件路径,通过查找/books/book[title='Java Programming']
这一表达式来检索所有标题为“Java Programming”的节点。 - NodeList 遍历:
XPathConstants.NODESET
返回NodeList
,遍历这些节点并输出相关信息。
扩展知识
- 第三方库:
DOM4J
、JDOM
等库提供了更高效的解析方式,并支持更多特性。 - 验证:使用
Schema
或DTD
来验证 XML 的格式。 - 序列化:输出处理后的 XML 文件,可使用
Transformer
之类的工具。