Reading XML elements content with DOM4J

SaintLike picture SaintLike · Jun 11, 2013 · Viewed 9.6k times · Source

I need some help.

I have the following XML file:

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

<simulation>
  <member id="House">
    <id>1</id>
    <agent_name>1</agent_name>
    <type>1</type>
    <max_usage>1</max_usage>
    <min_usage>1</min_usage>
    <average_usage>1</average_usage>
  </member>
  <member id="CSP">
    <id>2</id>
    <agent_name>2</agent_name>
    <type>2</type>
  </member>
  <member id="VPP">
    <id>3</id>
    <agent_name>3</agent_name>
    <type>3</type>
  </member>
</simulation>

I'm trying to save the numbers into an ArrayList<String> like this: {1,1,1,1,1,1,2,2,2,3,3,3}

However I'm having trouble doing it.

Here's my code:

public static void readSimulation(){
        Element root = doc.getRootElement();
        DefaultListModel tempList = new DefaultListModel();
        ArrayList<String> tempAL = new ArrayList();

        for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
            Element element = (Element) i.next();
            tempList.addElement(element.attributeValue("id")); 
            tempAL.add(element.getData().toString()); //I think this is the line that doesn't work
        }

        pt.ipp.isep.gecad.masgrip.Simulation.setDlm(tempList);
        pt.ipp.isep.gecad.masgrip.Simulation.setComponentsFromXML(tempAL);
}

I've tryed to print the content of tempAL and the output is this:

[






  , 



  , 



  ]
  [






  , 



  , 



  ]
  [






  , 



  , 



  ]

I don't know why, can you please help me to get the expected content from XML?

Answer

Michael Freake picture Michael Freake · Jun 11, 2013

The problem is that you are iterating through the children of simulation only. In other words, you are only looking at the 3 member elements rather than their children.

The empty space stored in your ArrayList is the text (white space, hard returns, etc) that you are using to nicely format the child nodes of the member elements.

You can complete your parsing by adding another loop within your for loop. Something like this:

    for ( Iterator i = root.elementIterator(); i.hasNext(); ) {
        Element element = (Element) i.next();
        tempList.addElement(element.attributeValue("id")); 

        for ( Iterator j = element.elementIterator(); j.hasNext(); ) {
            Element innerElement = (Element) j.next();
            tempAL.add(innerElement.getData().toString()); 
        }
    }