文章非个人原创,内容copy自:[易百教程]https://www.yiibai.com/java_xml/java_xpath_parser.html
XPath是万维网联盟(W3C)的官方推荐。它定义了一个语言在XML文件中查找信息。它被用于遍历XML文档的元素和属性。 XPath提供各种类型,可用于从XML文档查询相关的信息表现形式。
XPath使用步骤
1.导入XML相关的软件包
import org.w3c.dom.*;import org.xml.sax.*;import javax.xml.parsers.*;import javax.xml.xpath.*;import java.io.*;
2.创建DocumentBuilder
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder= factory.newDocumentBuilder();
3.从文件或数据流创建一个文档
StringBuilder xmlStringBuilder = newStringBuilder();
xmlStringBuilder.append("<?xml version="1.0"?> ");
ByteArrayInputStream input= newByteArrayInputStream(
xmlStringBuilder.toString().getBytes("UTF-8"));
Document doc= builder.parse(input);
4.创建XPath对象
XPath xPath = XPathFactory.newInstance().newXPath();
5.编译XPath表达式使用XPath.compile() ,并由XPath.evaluate()评估计算获得一个节点列表
String expression = "/class/student";
NodeList nodeList= (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);
6.遍历节点列表。
for (int i = 0; i < nodeList.getLength(); i++) {
Node nNode=nodeList.item(i);
...
}
7.检查属性
//returns specific attribute
getAttribute("attributeName");//returns a Map (table) of names/values
getAttributes();
8.检查子元素
//returns a list of subelements of specified name
getElementsByTagName("subelementName");//returns a list of all child nodes
getChildNodes();
demo案例
xml.txt
dinkar
kad
dinkar
85
Vaneet
Gupta
vinni
95
jasvir
singh
jazz
90
XPathParserDemo.java
importjava.io.File;importjava.io.IOException;importjavax.xml.parsers.DocumentBuilderFactory;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.ParserConfigurationException;importjavax.xml.xpath.XPath;importjavax.xml.xpath.XPathConstants;importjavax.xml.xpath.XPathExpressionException;importjavax.xml.xpath.XPathFactory;importorg.w3c.dom.Document;importorg.w3c.dom.NodeList;importorg.w3c.dom.Node;importorg.w3c.dom.Element;importorg.xml.sax.SAXException;public classXPathParserDemo {public static voidmain(String[] args) {try{
File inputFile= new File("./xml.txt");
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder=dbFactory.newDocumentBuilder();
Document doc=dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
XPath xPath=XPathFactory.newInstance().newXPath();
String expression= "/class/student";
NodeList nodeList=(NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET);for (int i = 0; i < nodeList.getLength(); i++) {
Node nNode=nodeList.item(i);
System.out.println("\nCurrent Element :"
+nNode.getNodeName());if (nNode.getNodeType() ==Node.ELEMENT_NODE) {
Element eElement=(Element) nNode;
System.out.println("Student roll no : "
+ eElement.getAttribute("rollno"));
System.out.println("First Name : "
+eElement
.getElementsByTagName("firstname")
.item(0)
.getTextContent());
System.out.println("Last Name : "
+eElement
.getElementsByTagName("lastname")
.item(0)
.getTextContent());
System.out.println("Nick Name : "
+eElement
.getElementsByTagName("nickname")
.item(0)
.getTextContent());
System.out.println("Marks : "
+eElement
.getElementsByTagName("marks")
.item(0)
.getTextContent());
}
}
}catch(ParserConfigurationException e) {
e.printStackTrace();
}catch(SAXException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(XPathExpressionException e) {
e.printStackTrace();
}
}
}
执行的结果:
Current Element :student
Student roll no : 393
First Name : dinkar
Last Name : kad
Nick Name : dinkar
Marks : 85
Current Element :student
Student roll no : 493
First Name : Vaneet
Last Name : Gupta
Nick Name : vinni
Marks : 95
Current Element :student
Student roll no : 593
First Name : jasvir
Last Name : singh
Nick Name : jazz
Marks : 90