使用Dom4j包读取XML文件

时间:2014-08-01 05:24:46

标签: xml dom4j

我有XML文件

<content>
     <std>
        <name>name1</name>
        <desc>desc1</desc>
        <sub>
           <sub1></sub1>
           <sub2></sub2>
        </sub>
     <std>
</content>

我正在尝试读取xml文件的Dom4j包

SAXReader reader = new SAXReader();
Document document;
InputStream stream = "./somthing/asd.xml";
document = reader.read(stream);

Element contentsElement = document.getRootElement();
List<Element> Elemet = contentsElement.elements();

for(Element itemElement : sourceElements){
    itemElement.elementTextTrim("name");
    itemElement.elementTextTrim("desc");
    List<Elements> subList = itemElement.elements("sub");
    //Can't go into loop because subList.size() value is 0
    for(Element e2 : subList){
           e2.elementTextTrim("sub1");
    }

}

如果正确读取数据,但我想了解<std>标签的详细信息 所以我会尝试评论专栏,但这不会有用,请指导我

1 个答案:

答案 0 :(得分:1)

下面的代码对我来说很好。

    SAXReader reader = new SAXReader();
    Document document = reader.read("a.xml");
    Element rootElement = document.getRootElement();        
    List<Element> list =  rootElement.elements("std");

    for (Element element : list) {
        System.out.println(element.elementTextTrim("name"));
        List<Element> sublist =  element.elements("sub");
        for (Element element2 : sublist) {
            System.out.println(element2.elementTextTrim("sub1"));
            System.out.println(element2.elementTextTrim("sub2"));
        }

    }

对于下面的a.xml: -

<content>
     <std>
        <name>name1</name>
        <desc>desc1</desc>
        <sub>
           <sub1>22</sub1>
           <sub2>223</sub2>
        </sub>
     </std>
</content>