簡體   English   中英

如何在Java中使用XPath解析XML

[英]How to parse XML using XPath in Java

結果,我想獲取一個TagName“控件”。 我正在使用XPath解析我的XML文件。 目前我只得到一個空白窗口,不知道為什么。

我的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) { }

預期輸出應為:

我的輸出:控制

您將獲得一個您正在默默消費的異常。 e.printStackTrace()添加到catch塊以了解其含義。

假設您解決了該問題,您似乎還使用xpath選擇了一個空元素(自動關閉)的文本內容。

如果要選擇元素的屬性值,則需要執行以下操作:

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

有關更多信息,請參見此SO帖子: 使用XPath獲取屬性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM