如何打印xml文件DOM4j库中可用的节点列表?

时间:2017-04-15 21:42:04

标签: java xml xml-parsing dom4j

我有一些xml文件,如下所示

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.shutterfly</groupId>
    <artifactId>CodingChallenges</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>CodingChallenges</name>
</project>

我想在下面打印出来:

输出为:

modelVersion 的groupId 的artifactId .. 名称 我试过的伪代码:

File inputFile = new File(inputFilePath);
SAXReader reader = new SAXReader();
Document document = reader.read(inputFile);
System.out.println("Root element :" + document.getRootElement().getName());
Element classElement = document.getRootElement();
@SuppressWarnings("unchecked")
List<Node> nodes = document.selectNodes("/project");
for (Node node : nodes) {
    System.out.println("\nCurrent Element :" + node.getName());
}
for (Iterator i = classElement.attributeIterator(); i.hasNext();) {
    Attribute attribute = (Attribute) i.next();
    System.out.println(attribute.getName());
}

1 个答案:

答案 0 :(得分:0)

也许这么简单:

    List<Node> nodes = document.selectNodes("/project/*");
    for (Node node : nodes) {
        System.out.println(node.getName() + "=" + node.getText());
    }