作者:陶玲英漂亮_607 | 来源:互联网 | 2017-05-14 02:24
代码片段,代码分享,PHP代码分享,Java代码分享,Ruby代码分享,Python代码分享,HTML代码分享,CSS代码分享,SQL代码分享,JavaScript代码分享
import java.io.File;
import java.io.FileInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class FindElementsByAbsoluteLocationWithXPath {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new FileInputStream(new File("in.xml")));
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
String expression;
Node node;
NodeList nodeList;
// 1. root element
expression = "/*";
node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
System.out.println("1. " + node.getNodeName());
// 2. root element (by name)
expression = "/rss";
node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
System.out.println("2. " + node.getNodeName());
// 3. element under rss
expression = "/rss/channel";
node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
System.out.println("3. " + node.getNodeName());
// 4. all elements under rss/channel
expression = "/rss/channel/*";
nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
System.out.print("4. ");
for (int i = 0; i Input:
en-us
-
http://www.javacodegeeks.com/</link>
-
http://examples.javacodegeeks.com/</link>
输出:
1. rss
2. rss
3. channel
4. title language item item
5. title title title
6. rss channel language item link item link
7. rss channel item item
8. title link title link
以上就是java通过XPath解析xml节点的代码详解的详细内容,更多请关注 第一PHP社区 其它相关文章!