Java – Dom4j Select Child Node

Tags: ,



I use Dom4j to parse XML data.. How can I get pos value in child node tileX, tileY, and skip if empty?

data/background_item.xml:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <item>
        <id>0</id>
        <layer>1</layer>
        <dx>-17</dx>
        <dy>-3</dy>
        <tileX>
            <pos>1</pos>
            <pos>2</pos>
        </tileX>
        <tileY>
            <pos>1</pos>
            <pos>2</pos>
        </tileY>
    </item>
    <item>
        <id>1</id>
        <layer>4</layer>
        <dx>1</dx>
        <dy>5</dy>
        <tileX></tileX>
        <tileY></tileY>
    </item>
</root>

Java code:

try {
    ArrayList<BgItem> bgItem = new ArrayList<>();
    SAXReader reader = new SAXReader();
    Document doc = reader.read(new File("data/background_item.xml"));
    Element root = doc.getRootElement();
    Iterator<Element> it = root.elementIterator();
    while (it.hasNext()) {
        Element el = it.next();
        BgItem bg = new BgItem();
        bg.id = Short.parseShort(el.elementTextTrim("id"));
        bg.layer = Byte.parseByte(el.elementTextTrim("layer"));
        bg.dx = Integer.parseInt(el.elementTextTrim("dx"));
        bg.dy = Integer.parseInt(el.elementTextTrim("dy"));
        bg.tileX = new ArrayList<>();
        bg.tileY = new ArrayList<>();
        
        // select tileX, tileY node ???
        
        bgItem.add(bg);
    }
    System.out.println("- Total background item: " + bgItem.size());
} catch (IOException | DocumentException | NumberFormatException e) {
    e.printStackTrace(System.out);
}

Answer

Inside your while loop, it should looks like this:

    Element xTileEle = el.element("tileX");
    for (Object posEle : xTileEle.elements("pos")) {
        tileX.add(((Element)posEle).getTextTrim());
    }

To skip the empty, just check whether the xTileEle is null.



Source: stackoverflow