如何在Java中使用XPath解析XML?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (142)

XML文件:

<tags>
  <row Id="1" TagName="soccer" Count="7" ExcerptPostId="12371" WikiPostId="12370" />
  <row Id="2" TagName="servos" Count="63" ExcerptPostId="186" WikiPostId="185" />
  <row Id="3" TagName="control" Count="394" ExcerptPostId="192" WikiPostId="191" />
  <row Id="5" TagName="gait" Count="4" ExcerptPostId="12362" WikiPostId="12361" />
</tags>Main.java
String uri = "/home/files/Tags.xml";

try {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(uri);
    XPath xPath = XPathFactory.newInstance().newXPath();

    String output = (String) xPath.evaluate("/tags/row[@TagName='control']", doc.getDocumentElement(),
            XPathConstants.STRING);
    System.out.println("My output:" + output);
} catch (IOException | ParserConfigurationException | XPathExpressionException | SAXException e) { }
提问于
用户回答回答于

执行以下操作:

/tags/row[@TagName='control']/@TagName

扫码关注云+社区

领取腾讯云代金券