【发布时间】:2018-06-14 22:23:29
【问题描述】:
我想得到一个标签名“控件”。我正在使用 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) { }
预期的输出应该是:
我的输出:控制
【问题讨论】:
-
你试过调试吗?你有什么例外吗?
-
同时在你的catch块中临时添加e.printStackTrace(),这样你就可以看到可能抛出了什么异常。
-
只有一个字:控制
-
是的,“我的输出:控制”
-
您的 xpath 应该以双斜杠
//tags开头。