Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create XML file from a list of objects in Java?

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?

like image 454
Pranav Avatar asked Jul 13 '12 11:07

Pranav


People also ask

How do you write the contents of Arraylist to XML file in Java?

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.


2 Answers

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

like image 122
Pita Avatar answered Oct 08 '22 02:10

Pita


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

like image 31
MattR Avatar answered Oct 08 '22 04:10

MattR