注意事項
* 下記のサンプルの「@XmlRootElement(name = "people" )」が重要で、ここで、XMLのルート要素を定義してあげる * プロパティに、Listのクラスを使用してもファイル出力するには、「@XmlElement」が必要 ----- @XmlElement private List<Person> friends; ----- => これがないと、該当するプロパティがファイル出力されない。
サンプル
People.java
import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "people") public class People { public List<Person> people; public People() { this.people = new ArrayList<Person>(); } }
Person.java
public class Person { private String name; private int age; @XmlElement private List<Person> friends; public Person() { this.friends = new ArrayList<Person>(); } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } public List<Person> getFriends() { return this.friends; } public void addFriend(Person person) { this.friends.add(person); } }
HelloJaxb.java
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import javax.xml.bind.JAXB; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; public class HelloJaxb { public static void main(String[] args) { People p = new People(); Person person1 = new Person(); person1.setName("Ken"); person1.setAge(62); p.people.add(person1); Person person2 = new Person(); person2.setName("Coco"); person2.setAge(10); p.people.add(person2); // 書き込み try { JAXB.marshal(p, new FileOutputStream("people.xml")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 読み込み try { InputStream xmlInputStream = new FileInputStream("people.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(People.class); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); People newPeople = (People)unmarshaller.unmarshal(xmlInputStream); for (Person person : newPeople.people) { System.out.println(person.getName() + "(" + person.getAge()+ ")"); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
出力
Ken(62) Coco(10)
参考文献
http://www.akirakoyasu.net/2011/02/27/251/http://theopentutorials.com/tutorials/java/jaxb/jaxb-marshalling-and-unmarshalling-list-of-objects/
http://d.hatena.ne.jp/torutk/20111001/p1