使用 xPath 从 XML 创建 java 树对象

Create java tree object from XML with xPath

所以,这是我的问题:我想使用 xPath 表达式和算法解析 XML 文件以创建我的对象 (List< Team >)。

我的 class 是这样定义的:

public class Team {

    private String itemId;
    private String name;
    private boolean archived;
    private List<Team> children;

    public Team(String itemId, String name, boolean archived) {
        this.children = new ArrayList<TeamArea>();
        this.itemId = itemId;
        this.name = name;
        this.archived = archived;
    }

    // getters and setters
}

这里是XML结构的一个例子:(一个子节点可以有0到n个子节点)

<children>
    <itemId>first team</itemId>
    <name>first team</name>
    <archived>first team</archived>
    <children>
        <itemId>first child of first team</itemId>
        <name>first child of first team</name>
        <archived>first child of first team</archived>
    </children>
</children>
<children>
    <itemId>second team</itemId>
    <name>second team</name>
    <archived>second team</archived>
    <children>
        <itemId>first child of second team</itemId>
        <name>first child of second team</name>
        <archived>first child of second team</archived>
        <children>
            <itemId>first child of child above</itemId>
            <name>first child of child above</name>
            <archived>first child of child above</archived>
        </children>
    </children>
</children>

我使用 org.w3c.dom.Node 和 NodeList 接口。 我尝试使用 xPath 表达式://children/node() 但我无法浏览 NodeList 来创建我的 List< Team > 对象。

有人可以帮我解决算法和要使用的 xpath 表达式吗?

谢谢!

从 XPath 开始:

//children[not(parent::children)]

然后 foreach children 使用 XPath:

children