How to create XML file from a list of objects in Java?
Solution 1
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
Solution 2
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/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
Solution 3
One of the easiest ways to do this is simply iterate over the list and use strings to write the XML. Nothing special, very quick and easy.
Pranav
Updated on June 17, 2022Comments
-
Pranav almost 2 years
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 classEquipment
. Now, the attributes in the class ofEquipment
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?