1

私はこのXMLを持っています:

<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 ,sub110sub2 。-,-20

これどうやってするの?これまでのところ、私は子なしで要素を取得することしかできません。

4

2 に答える 2

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;
于 2012-08-01T08:54:36.157 に答える
3
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());;
            }
        }
    }
}
}

この出力は、myxml.xmlという名前のファイルに質問の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:ここで良いガイドを見つけました

于 2012-08-01T10:12:47.803 に答える