TestModel.java
package upmover.schema.model;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
@XmlRootElement(name="root")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TestModel")
public class TestModel {
@XmlValue
private String msg;
public void setMsg(String msg) {
this.msg=msg;
}
public String getMsg() {
return msg;
}
public static void main(String[] args) throws Exception {
unmarshal();
}
//marshal -- from java object to xml
public void marchal() throws Exception {
JAXBContext JContext=JAXBContext.newInstance(TestModel.class.getPackage().getName());
TestModel helloT=new TestModel();
helloT.setMsg("Define a model");
Marshaller m=JContext.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
StringWriter writer=new StringWriter();
m.marshal(helloT, writer);
String outputXml=writer.toString();
System.out.println("xml output:\n"+outputXml);
//output: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
// <root>Define a model</root>
}
//unmarshal -- from xml to java object
public static void unmarshal() throws Exception {
JAXBContext JContext=JAXBContext.newInstance(TestModel.class.getPackage().getName());
Unmarshaller um=JContext.createUnmarshaller();
XMLInputFactory f = XMLInputFactory.newInstance();
String xml="<root>the content</root>";
XMLStreamReader in=f.createXMLStreamReader(new StringReader(xml));
JAXBElement<TestModel> jaxbElement=um.unmarshal(in, TestModel.class);
TestModel h=jaxbElement.getValue();
System.out.println(" HelloType.getMsg(): "+h.getMsg());
}
}