Java使用Xpath解析XML多级使用Xpath
问题描述:
你好,我试图解析下面的XML代码,我只需要一个极性值,在这种情况下,我需要N +,但是我得到3倍的N +值。Java使用Xpath解析XML多级使用Xpath
<tweet>
<tweetid>----</tweetid>
<user>----</user>
<date>2011-12-02T02:33:37</date>
<lang>es</lang>
<sentiments>
<polarity><value>N+</value><type>AGREEMENT</type></polarity>
<polarity><entity>Sinde</entity><value>N+</value><type>AGREEMENT</type></polarity>
<polarity><entity>SGAE</entity><value>N+</value><type>AGREEMENT</type></polarity>
</sentiments>
<topics>
<topic>política</topic>
<topic>economía</topic>
</topics>
</tweet>
<tweet>
,我使用此代码:
String expression3 = "/tweets/tweet/sentiments/polarity/value[1]";
NodeList nodeList3 = (NodeList) xPath.compile(expression3).evaluate(doc, XPathConstants.NODESET);
for (int j = 0; j < 10; j++){
System.out.println(j + "--" +nodeList3.item(j).getFirstChild().toString());
}
但我得到以下输出。
0--[#text: N+]
1--[#text: N+]
2--[#text: N+]
如何只使用XPath获取一个?因为当我建立我的out.txt时,我只需要其中一个极性值,因为在每条推文中只有一个值,因此,所有的推文都会搞砸。我一直在尝试不同的表情,但我不明白,
谢谢。
答
用“/ tweets/tweet/sentiments/polarity/value [1]”这个词来表示“给mi命名的第一个节点,每个节点都叫极性”,如果你想获得值的节点第一个极性节点试着用/ tweets/tweet/sentiments/polarity [1]/value
我把极性[1] /值代替极性/值[1],它起作用了 – Charliocat