Getting amount of children with XOM

248 Views Asked by At
<?xml version="1.0" encoding="UTF-8"?>
<locations>
    <location id="83">
        <location_name>name</location_name>
        <company_name>company a</company_name>
        <machines>
            <machine id="12">A</machine>
            <machine id="312">B</machine>
        </machines>
    </location>
    <location id="85">
        <location_name>name</location_name>
        <company_name>company c</company_name>
        <machines>
            <machine id="21">A</machine>
            <machine id="45">B</machine>
        </machines>
    </location>
</locations>

I'm using XOM and trying to get all location names but I don't know how.

Element root = doc.getRootElement();    
int i = 1;
Element child = (Element) root.getChild(i);
while(child != null)
{
    System.out.println(child.getFirstChildElement("location_name").getValue());
    child = (Element) root.getChild(i++);
}

But this don't work, it shows only the first name, on second loop it shows error.

And secound question: what getChildCount() counts??

1

There are 1 best solutions below

0
On BEST ANSWER

getChild(int i) returns the i-th child node, not necessarily the i-th child element. Use getChildElements("location") and iterate over the list returned. Another approach is to use an XPath query on the root element.

Also, the javadoc is quite informational: http://www.xom.nu/apidocs/.