2013-12-17 72 views
1

你好,我試圖解析下面的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時,我只需要其中一個極性值,因爲在每條推文中只有一個值,因此,所有的推文都會搞砸。我一直在嘗試不同的表情,但我不明白,

謝謝。

+0

我把極性[1] /值代替極性/值[1],它起作用了 – Charliocat

回答

1

用「/ tweets/tweet/sentiments/polarity/value [1]」這個詞來表示「給mi命名的第一個節點,每個節點都叫極性」,如果你想獲得值的節點第一個極性節點試着用/ tweets/tweet/sentiments/polarity [1]/value