原文: https://howtodoinjava.com/xml/evaluate-xpath-on-xml-string/
Java 示例求值字符串上的 xpath 并返回字符串本身的结果 XML。
1. XPath 示例 – 在 xml 字符串上求值 xpath
- 创建包含
StringReader
并引用 XML 字符串的org.xml.sax.InputSource
。 - 从
XPathFactory
创建XPath
。 - 使用
xpath.evaluate('expression', inputSource)
获取结果 HTML。
package com.howtodoinjava.demo;
import java.io.StringReader;
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;
import org.xml.sax.InputSource;
public class XPathExample
{
public static void main(String[] args) throws Exception
{
String xml = "<employees>"
+ "<employee id=\"1\">"
+ "<firstName>Lokesh</firstName>"
+ "<lastName>Gupta</lastName>"
+ "<department><id>101</id><name>IT</name></department>"
+ "</employee>"
+ "</employees>";
InputSource inputXML = new InputSource( new StringReader( xml ) );
XPath xPath = XPathFactory.newInstance().newXPath();
String result = xPath.evaluate("/employees/employee/firstName", inputXML);
System.out.println(result);
}
}
程序输出:
Lokesh
2. XPath 示例 – 在 xml 文件上求值 xpath
package com.howtodoinjava.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>
在上面的 Xpath 教程中,我们学习了使用示例求值字符串上的 xpath 的方法。
学习愉快!
阅读更多: