Let's say I want to create this xml:
<root>
<element>
text 1
</element>
<element>
text 2
</element>
<element>
text 3
</element>
.
.
.
n elements
</root>
With a java loop, I having trouble creating it with jdom.element, since at the second iteration, it says that there's already an element called "element", and I have read that once attached, you can't create more of the same element, so use clone or something, but I haven't figure out how, and I believe this should be fairly simple.
int i = 0;
int n = 100;
while(i < n){
(Missing code)
}
Missing code is what I need.
EDIT: Sorry for being lazy, I've added code to exemplify better what I needed to do, and what worked, but @rolfl understood what I wanted to do and my problem, and he solved it. Thank you. And sorry again everyone for being lazy.
My code:
Element eElements = new org.jdom.Element("Elements");
Element eElement;
Element eSubElement1 = new org.jdom.Element("SubElement1");
Element eSubElement2 = new org.jdom.Element("SubElement2");
int i = 0;
int n = 100;
while (i < n){
eSubElement1.setText("Text " + i);
eSubElement2.setText("Text " + i);
eElement = new org.jdom.Element("Element");
eElement.addContent(eSubElement1);
eElement.addContent(eSubElement2);
eElements.addContent(eElement);
}
I thought that calling a new "Element" everytime would be enough, but you have to call new "SubElementX" too.
While loop that worked:
while (i < n){
eSubElement1 = new org.jdom.Element("SubElement1").setText("Text " + i);
eSubElement2 = new org.jdom.Element("SubElement2").setText("Text " + i);
eElement = new org.jdom.Element("Element");
eElement.addContent(eSubElement1);
eElement.addContent(eSubElement2);
eElements.addContent(eElement);
}
You are obviously trying to add the same instance multiple times, or something. You should create a new instance of the Element "element" for each value.
Something like:
Then output the
root
element usingXMLOutputter
(Use theFormat.getPrettyFormat()
on your outputter to get nice whitespace in the results.