Marshaller和Unmarshaller用法示例

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
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 JAXBException, FileNotFoundException{

JAXBContext jc = JAXBContext.newInstance(Instance.class);
Unmarshaller u = jc.createUnmarshaller();
// Object element = u.unmarshal( new File( "foo.xml" ) );
Object element = new Instance();
Marshaller m = jc.createMarshaller();
OutputStream os = new FileOutputStream( "nosferatu.xml" );
m.marshal( element, os );




}
}


@XmlRootElement(name = "root")
@XmlType(propOrder={"name", "gender", "age"})
class Instance
{

private String name;
private int age;
private String gender;

public Instance()
{
this.name = "abc";
this.age = 15;
this.gender = "male";
}

@XmlElement(name="userName", nillable=true, required=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}

你可能感兴趣的:(java)