Search code examples
javaxmljdom

Cannot get children attributes with JDOM from XML


I'm trying to get the name of each person in the example XML file but I'm getting null values instead of their names.

Java code:

package testjdom;

import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

public class TestJDOM {

    public static void main(String[] args) throws
            JDOMException,
            IOException {

        SAXBuilder jdomBuilder
                = new SAXBuilder();
        Document jdomDocument
                = jdomBuilder.build("persons.xml");

        Element jdomRoot = jdomDocument.getRootElement();

        List<Element> children = jdomRoot.getChildren();
        for (Element child : children) {
            System.out.println(child.getAttributeValue("name"));
        }
    }
}

XML:

<?xml version="1.0" encoding="UTF-8"?>
<persons>
  <person>
    <id>1</id>
    <name>The Best</name>
    <email>[email protected]</email>
    <birthDate>1981-11-23</birthDate>
  </person>
  <person>
    <id>2</id>
    <name>Andy Jr.</name>
    <email>[email protected]</email>
    <birthDate>1982-12-01</birthDate>
  </person>
  <person>
    <id>3</id>
    <name>JohnDoe</name>
    <email>[email protected]</email>
    <birthDate>1990-01-02</birthDate>
  </person>
  <person>
    <id>4</id>
    <name>SomeOne</name>
    <email>[email protected]</email>
    <birthDate>1988-01-22</birthDate>
  </person>
  <person>
    <id>5</id>
    <name>Mr. Mxyzptlk</name>
    <email>[email protected]</email>
    <birthDate>1977-08-12</birthDate>
  </person>
</persons>

How can I get the true value of each name?

Ultimately I'd like to get the four values of each person from the XML. I have a class called Person, it has the same attributes as the persons have in the XML file, id, name, etc. I'd like to create new objects from the "Person" class and set the values of their attributes with the data in the XML. When I created a new object and successfully set its attributes with the values I got from the XML, I'd like to add the object to an ArrayList then repeat the same process with the remaining persons.


Solution

  • You have two problems. name is not an attribute, it is a child element. Second, getChildren() goes down only one level.

    Change

        Element jdomRoot = jdomDocument.getRootElement();
    
        List<Element> children = jdomRoot.getChildren();
        for (Element child : children) {
            System.out.println(child.getAttributeValue("name"));
        }
    

    to

        Element jdomRoot = jdomDocument.getRootElement();
    
        List<Element> people = jdomRoot.getDescendants(new ElementFilter("person"));
        for (Element person: people) {
            System.out.println(person.getChild("name").getText());
        }