I want to create one XML file from one list of objects. Objects are having some attributes, so the tags will be the attribute names and the respective data will be inside the tag.
This is example:
I have one List myEquipmentList
, that contains 100 objects of the class Equipment
. Now, the attributes in the class of Equipment
are id, name, size, measures, unit_of_measure etc.
Now I want to create XML which will be something like this.
<Equipment id=1>``
<name>Ruler</name>
<size>1000</size>
<measures>length</measures>
<unit_of_measure>meter</unit_of_measure>
</Equipment>
Any ideas?
You would need to iterate by steps of 3 in the loop, and get the elements i, i+1 and i+2 to make it work. Show activity on this post. But you would probably be better off storing in your list objects of a custom class, with dedicated fields for name, id and age. Show activity on this post.
you can create a class with the list of objects, then serialise the list to xml and finally deserialise xml to a list.
Please see this link - Very useful: How to convert List of Object to XML doc using XStream
Read about JAXB.
You could have a class like this that would generate the XML you want:
@XmlRootElement
public class Equipment {
private Long id;
private String name;
private Integer size;
...etc...
@XmlAttribute
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
... etc...
}
You'll find plenty of info on JAXB on google on searching on stackoverflow.
http://jaxb.java.net/
http://jaxb.java.net/tutorial/
These look like a couple of simple tutorials:
http://www.mkyong.com/java/jaxb-hello-world-example/
http://www.vogella.com/articles/JAXB/article.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With