评估字符串上的xpath并返回字符串本身中的结果XML的Java示例。
1. XPath example – Evaluate xpath on xml stringpackage 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 = ""
+ ""
+ "Lokesh"
+ "Gupta"
+ "101IT"
+ ""
+ "";
InputSource inputXML = new InputSource( new StringReader( xml ) );
XPath xPath = XPathFactory.newInstance().newXPath();
String result = xPath.evaluate("/employees/employee/firstName", inputXML);
System.out.println(result);
}
}
Program output:
Lokesh
2. XPath example – Evaluate xpath on xml filepackage 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
}
}
}
Program output:Lokesh
1
2
输入的xml文件为:<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
Lokesh
Gupta
101
IT
Brian
Schultz
102
HR
在上面的Xpath教程中,我们学习了使用示例评估字符串上的xpath的方法。
Read More: