JSR 222 (JAXB 2.0)
JAXB chapter of the Java EE 5 Tutorial
JDK 1.6 javax.xml.bind
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Date;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
public class Main {
public static void main(String[] args) throws Exception {
Foo foo = new Foo();
foo.fb = new FooBar();
foo.fb.x = 2;
foo.fb.y = 3;
foo.fb.date = new Date();
JAXBContext jc = JAXBContext.newInstance(Foo.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty("jaxb.formatted.output", true);
marshaller.marshal(foo, System.out);
System.out.println();
StringWriter sw = new StringWriter();
sw.write("<foo><fb>");
sw.write("<x>15</x>");
sw.write("<date>2009-01-16T17:50:50.000+08:00</date>");
sw.write("</fb></foo>");
StringReader sr = new StringReader(sw.toString());
foo = (Foo)jc.createUnmarshaller().unmarshal(sr);
System.out.println("x: " + foo.fb.x);
System.out.println("date: " + foo.fb.date);
}
}
@XmlRootElement
class Foo {
@XmlElement
FooBar fb;
}
@XmlType
class FooBar {
@XmlElement
int x;
@XmlAttribute
int y;
@XmlElement
Date date;
}
/*
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
<fb y="3">
<x>2</x>
<date>2009-01-16T22:06:24.763+08:00</date>
</fb>
</foo>
x: 15
date: Fri Jan 16 17:50:50 CST 2009
*/
沒有留言:
張貼留言