「Java開発」@XmlRootElementを利用するサンプル

@XmlRootElement
クラスまたは列挙型を XML 要素にマップします。

javaコード:
1.Student.java
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {
String name = “suzuki";

}

2.mainメソッド
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class JAXBDemo {

public static void main(String[] args) throws JAXBException {
JAXBContext context = null;
try {
context = JAXBContext.newInstance(Student.class);
} catch (JAXBException e) {

e.printStackTrace();
}

Marshaller marshaller = context.createMarshaller();
Unmarshaller unmarshaller = context.createUnmarshaller();

Student stu = new Student();
marshaller.marshal(stu, System.out);
System.out.println();

String xml = “<student><name>yamada</name></student>";
Student stu2 = (Student) unmarshaller.unmarshal(new StringReader(xml));
System.out.println(stu2.name);

}

}
3.実行結果
<?xml version="1.0″ encoding="UTF-8″ standalone="yes"?><student><name>suzuki</name></student>
yamada

Java

Posted by arkgame