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?


<?xml version="1.0" encoding="UTF-8"?>

Java code:

try {
    ArrayList<BgItem> bgItem = new ArrayList<>();
    SAXReader reader = new SAXReader();
    Document doc = File("data/background_item.xml"));
    Element root = doc.getRootElement();
    Iterator<Element> it = root.elementIterator();
    while (it.hasNext()) {
        Element el =;
        BgItem bg = new BgItem(); = 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 ???
    System.out.println("- Total background item: " + bgItem.size());
} catch (IOException | DocumentException | NumberFormatException e) {


Inside your while loop, it should looks like this:

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

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

Source: stackoverflow