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 = "*/*/*"; nodeList = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET); System.out.print("8. "); for (int i = 0; i < nodeList.getLength(); i++) { System.out.print(nodeList.item(i).getNodeName() + " "); } System.out.println(); } }Input:
Java Tutorials and Examples 2 en-us http://www.javacodegeeks.com/ http://examples.javacodegeeks.com/
输出:
1. rss2. rss3. channel4. title language item item5. title title title6. rss channel language item link item link7. rss channel item item8. title link title link
以上就是java通过XPath解析xml节点的代码详解的详细内容,更多请关注考高分网其它相关文章!



