Java如何使用xpath表达式查询xml节点文本
使用Java进行XPath查询XML节点文本可以借助于Java内置的XML解析器和XPath表达式。以下是一个XML样例和Java代码示例: XML样例: ```xml <root> <book> <title>Java编程</title> <author>John Doe</author> <year>2019</year> </book> <book> <title>Python入门</title> <author>Jane Smith</author> <year>2018</year> </book> </root> ``` Java样例代码: ```java import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; public class XPathExample { public static void main(String[] args) { try { // 创建XML文档解析器 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = factory.newDocumentBuilder().parse("path_to_xml_file"); // 将xml文件路径替换为实际的路径 // 创建XPath对象 XPath xpath = XPathFactory.newInstance().newXPath(); // 创建XPath表达式 XPathExpression expression = xpath.compile("//book/title/text()"); // 执行XPath表达式并获取结果 NodeList nodeList = (NodeList) expression.evaluate(doc, XPathConstants.NODESET); // 遍历结果并输出节点文本 for (int i = 0; i < nodeList.getLength(); i++) { System.out.println(nodeList.item(i).getNodeValue()); } } catch (Exception e) { e.printStackTrace(); } } } ``` 这个示例中使用了Java的内置XML解析器和XPath支持。可以通过引入以下maven依赖以使用这些类: ```xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency> ```