2012-04-11 115 views
0

了迭代的節點的XPath的價值我有一個XML掌握在Java中

<?xml version="1.0" encoding="UTF-8"?> 
<information> 
    <person id="1"> 
    <name>Deep</name> 
    <age>34</age> 
    <gender>Male</gender> 
    </person> 

<person id="2"> 
    <name>Kumar</name> 
    <age>24</age> 
    <gender>Male</gender> 
    </person> 

    <person id="3"> 
    <name>Deepali</name> 
    <age>19</age> 
    <gender>Female</gender> 
    </person> 

    <!-- more persons... --> 
</information> 
DocumentBuilderFactory domFactory = DocumentBuilderFactory 
       .newInstance(); 
     domFactory.setNamespaceAware(true); 
     DocumentBuilder builder = domFactory.newDocumentBuilder(); 
     Document doc = builder.parse("persons.xml"); 
     XPath xpath = XPathFactory.newInstance().newXPath(); 
     // XPath Query for showing all nodes value 
     XPathExpression expr = xpath.compile("//information/person[0]/name/text()"); 

     Object result = expr.evaluate(doc, XPathConstants.NODE); 
     Node node = (Node) result; 
     System.out.println(node.getNodeValue()); 

,我需要提取的第一人我想上面的代碼名稱它給例外任何一個可以幫我在這,

修訂 異常

Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredTextImpl cannot be cast to javax.xml.soap.Node 
    at xml.main(xml.java:33) 

修訂ANSWER

XPathExpression expr = xpath.compile("//information/person[1]/name"); 

     String str = (String) expr.evaluate(doc, XPathConstants.STRING); 

     System.out.println(str); 
+1

什麼異常? – McDowell 2012-04-11 18:12:50

+1

拉梅什,假設我去看了醫生,說:「我覺得噁心,但我不會告訴你我的症狀,你能幫我嗎?」 – LarsH 2012-04-11 18:48:18

+0

對不起,不提供例外。我已經更新了這個問題,請看看 – Ramesh 2012-04-12 04:06:37

回答

1

的XPath索引開始在基地1個,不爲0,因爲大多數會認爲,這樣的人[0]將不會返回任何東西。 您的XPath更改爲//information/person[1]/name/text() 你也可以指定避免簡單地完全使用靜態數字的位置://information/person[position()=1]/name/text()

//information/person[@id='1']/name/text()如果通過ID需要它。

+1

[1]只是[position()= 1]的簡寫。它不像「數組索引」那樣索引。 – 2012-04-11 18:49:38

+0

你說得對,這是一個節點列表,而不是一個數組,position()與數組中的索引不同。我們不使用陣列好事;) – JWiley 2012-04-11 19:09:29

+0

@jdwilemo:我認爲,馬爾科是在迴應你的說法:「你也可以指定完全避免索引的位置」。他的觀點是你沒有避免任何事情......''[1]'和'[position()= 1]'完全相同。 – LarsH 2012-04-12 17:06:13

1

XPathExpression EXPR = xpath.compile( 「//信息/人[1] /名稱」);

String str = (String) expr.evaluate(doc, XPathConstants.STRING); 

    System.out.println(str);