Xpath解析xml

 

xml文件:

<datas>
 <data>
 <id>10089</id>
 <name>test1</name>
 <type>employee</type>
 </data>
</datas>

 

public void pathToXml(String xml) {

  DocumentBuilderFactory domFactory = DocumentBuilderFactory
    .newInstance();
  domFactory.setNamespaceAware(true); // never forget this!
  try {
   DocumentBuilder builder = domFactory.newDocumentBuilder();
   Document doc = builder.parse("test.xml");

   XPathFactory factory = XPathFactory.newInstance();
   XPath xpath = factory.newXPath();
   XPathExpression expr = xpath
     .compile("//data[id='10089']/name/text()");

   Object result = expr.evaluate(doc, XPathConstants.NODESET);
   NodeList nodes = (NodeList) result;
   for (int i = 0; i < nodes.getLength(); i++) {
    System.out.println(nodes.item(i).getNodeValue());
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

你可能感兴趣的:(xpath)