Search code examples
javaxmlxpathnodelist

Create java tree object from XML with xPath


So, here is my problem: I want to parse XML file using xPath expressions and algorithms in order to create my object (List< Team >).

My class is defined like this :

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
}

Here an exemple of the XML structure : (a children node can have 0 to n sub children)

<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>

I use the org.w3c.dom.Node and NodeList interfaces. I tried to use the xPath expression : //children/node() but I can't manage to browse the NodeList to create my List< Team > object.

Could someone help me with the algorithm and the xpath expression to use ?

Thank you!


Solution

  • Start with XPath:

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

    And then foreach children use XPath:

    children