java使用XPath解析xml
2018-07-20 来源:open-open
XML文件:widgets.xml
<widgets> <widget value="widgetValue">widText</widget> </widgets>
public static void examineXmlFile(String path) throws Exception { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(path); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//node/@id"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); System.out.println(nodes.item(i).getNodeValue()); } }
另一个使用xPath的示例:ReadXMLbyXPath
package util.xml; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import com.sun.org.apache.xpath.internal.NodeSet; public class ReadXMLbyXPath { public static void main(String[] arg ) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException { // parse the XML as a W3C Document DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new File("E:/workspace/Java-Util/src/util/xml/widgets.xml")); XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/widgets/widget"; Node widgetNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE); System.out.println(widgetNode.getNodeName());//节点名称 System.out.println(widgetNode.getNodeValue());//节点值是null,为什么? System.out.println(widgetNode.getTextContent());//节点text } }
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:Java 判断两个日期相差多少天
下一篇:java实现截屏程序
最新资讯
热门推荐