0

I am trying to create multiple element with the same name using JDOM, the XML file should be output as following:

   <data>
    <series name="Related">
      <point name="aaaa" y="1" />
      <point name="bbbb" y="0" />
      <point name="cccc" y="2" />
      <point name="dddd" y="3" />          
    </series>

    <series name="Not-Related" >
     <point name="CE901" y="1" />
      <point name="aaa" y="1" />
      <point name="bbb" y="1" />
      <point name="rrr" y="1" />
      <point name="rrr" y="1" />
     </series>
   </data>

And I tried to code it as:

  for (int i = 0; i < 2; i++) {
  doc1.getRootElement().getChild("charts").getChild("chart").getChild("data").addContent(new Element("series").setAttribute("name", "Related"));             
            for (int j = 0; j < 4; j++) {
                doc1.getRootElement().getChild("charts").getChild("chart").getChild("data").getChild("series").addContent(new Element("point").setAttribute("name", "CE901").setAttribute("y","1"));              
            }
        }

However the above code output the following XML, which is wrong:

<data>
<series name="Related">
<point name="CE901" y="1"/>
<point name="CE901" y="1"/>
<point name="CE901" y="1"/>
<point name="CE901" y="1"/>  
<point name="CE901" y="1"/>
<point name="CE901" y="1"/>
<point name="CE901" y="1"/>
<point name="CE901" y="1"/>
</series>
<series name="Related"/>

Can you please help me to find such way precisely to write more than one elements with the same names using JDOM?

Thank you..

1 Answers1

0

getChild("data") returns the first child named "data". If you need to add something to the second child named "data", use getChildren(), and get the second element from the returned list.

Note that your code would be much more readable (and efficient) if you used variables instead of repeating the whole chain of getters each time:

Element chart = doc1.getRootElement().getChild("charts").getChild("chart");
for (int i = 0; i < 2; i++) {
    Element data = chart.getChildren("data").get(i);
    Element series = new Element("series").setAttribute("name", "Related");
    data.addContent(series);             
    for (int j = 0; j < 4; j++) {
        series.addContent(new Element("point").setAttribute("name", "CE901")
                                              .setAttribute("y","1"));              
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thank you for your answer. It does not work, It's compiled successfully and in the Console pane the messages said that Index: 1 Size: 1, but it didn't create xml file, although it used to be created before. Also, it requires me to add (Element) casting in assigning data variable, and I did that. – Ahmed Albashiri Jul 31 '12 at 19:08