2012-08-01 154 views
0

XML子元素,我有這樣的XML:掌握的XPath

<root> 
    <items> 
    <item1> 
     <tag1>1</tag1>    
     <sub> 
     <sub1>10 </sub1> 
     <sub2>20 </sub2> 
     </sub> 
    </item1> 

    <item2> 
     <tag1>1</tag1>    
     <sub> 
     <sub1> </sub1> 
     <sub2> </sub2> 
     </sub>   
    </item2> 
    </items> 
</root> 

我想要得到的子元素的item1元素的名稱和值。

也就是說,我想:tag1 - 1 , SUB1 SUB2 -20

我該怎麼做?到目前爲止,我只能得到沒有孩子的元素。

+0

中發現了一個很好的指南到目前爲止你有什麼嘗試?請包括您在問題中使用的XPath和Java代碼。 – 2012-08-01 08:49:26

回答

2
import org.w3c.dom.*; 
import javax.xml.parsers.*; 
import javax.xml.xpath.*; 
/** 
* File: Ex1.java @author ronda 
*/ 
public class Ex1 { 
public static void main(String[] args) throws Exception { 
    DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = Factory.newDocumentBuilder(); 
    Document doc = builder.parse("myxml.xml"); 

    //creating an XPathFactory: 
    XPathFactory factory = XPathFactory.newInstance(); 
    //using this factory to create an XPath object: 
    XPath xpath = factory.newXPath(); 

    // XPath Query for showing all nodes value 
    XPathExpression expr = xpath.compile("//" + "item1" + "/*"); 
    Object result = expr.evaluate(doc, XPathConstants.NODESET); 
    NodeList nodes = (NodeList) result; 
    System.out.println(nodes.getLength()); 
    for (int i = 0; i < nodes.getLength(); i++) { 

     Element el = (Element) nodes.item(i); 

     System.out.println("tag: " + el.getNodeName()); 
     // seach for the Text children 
     if (el.getFirstChild().getNodeType() == Node.TEXT_NODE) 
      System.out.println("inner value:" + el.getFirstChild().getNodeValue()); 

     NodeList children = el.getChildNodes(); 
     for (int k = 0; k < children.getLength(); k++) { 
      Node child = children.item(k); 
      if (child.getNodeType() != Node.TEXT_NODE) { 
       System.out.println("child tag: " + child.getNodeName()); 
       if (child.getFirstChild().getNodeType() == Node.TEXT_NODE) 
        System.out.println("inner child value:" + child.getFirstChild().getNodeValue());; 
      } 
     } 
    } 
} 
} 

我得到這個輸出負載你的問題的XML文件名爲:myxml.xml:

run: 
2 
tag: tag1 
inner value:1 
tag: sub 
inner value: 

child tag: sub1 
inner child value:10 
child tag: sub2 
inner child value:20 

...有點羅嗦,但是讓我們瞭解它是如何工作。 PS:我在here

4
Document doc = ...; 
XPath xpath = XPathFactory.newInstance().newXPath(); 
XPathExpression expr = xpath.compile("/root/items/item1/*/text()"); 
Object o = expr.evaluate(doc, XPathConstants.NODESET); 
NodeList list = (NodeList) o;