Java xpath 示例 读取 XML 文件并解析为 DOM 对象,然后评估 org.w3c.dom.Document
对象上的 xpath 并获得结果以 String
或 NodeList
的形式。
Document
DOM 对象 javax.xml.parsers.DocumentBuilder
对象。XPath
来自 XPathFactory
。xpath.evaluate('expression', dom, resultType)
获取结果 HTML。package com.cundage.demo; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; 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; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class XPathExample { public static void main(String[] args) throws Exception { String xmlFile = "employees.xml"; //Get DOM DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document xml = db.parse(xmlFile); //Get XPath XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); //Get first match String name = (String) xpath.evaluate("/employees/employee/firstName", xml, XPathConstants.STRING); System.out.println(name); //Lokesh //Get all matches NodeList nodes = (NodeList) xpath.evaluate("/employees/employee/@id", xml, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); //1 2 } } }
程序输出:
Lokesh 1 2
输入的 xml 文件是:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employees> <employee id="1"> <firstName>Lokesh</firstName> <lastName>Gupta</lastName> <department> <id>101</id> <name>IT</name> </department> </employee> <employee id="2"> <firstName>Brian</firstName> <lastName>Schultz</lastName> <department> <id>102</id> <name>HR</name> </department> </employee> </employees>
快乐学习!!
地址:https://www.cundage.com/article/evaluate-xpath-on-dom.html