1.在eclipse中创建JAXB工程,或者普通工程也行,只要导入相应的jar就可以了。
2.建立几个普通的JavaBean对象,不过这些JavaBean对象要做一些相应的处理(不要忘了打标价哦,下面例子会有的)
3.使用JAXB提供的API进行JavaBean和XML之间的呼唤。
4.代码演示:
JavaBean:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class User {
@XmlAttribute
private int age;
@XmlAttribute
private String userName = "";
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
测试类:
@Test
public void testField() throws Exception{
JAXBContext context = JAXBContext.newInstance(User.class);
Marshaller marshaller = context.createMarshaller();
Unmarshaller unmarshaller = context.createUnmarshaller();
User user = new User();
marshaller.marshal(user, System.out);
System.out.println();
System.out.println("================================================");
//String xml = "<user><age>28</age><userName>simier</userName></user>";
String xml = "<user age='123' userName='simier'></user>";
User u = (User)unmarshaller.unmarshal(new StringReader(xml));
System.out.println(u.getAge());
System.out.println(u.getUserName());
}
运行效果:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><user userName="" age="0"/>
================================================
123
simier
JavaBean中有接口类型的情况:
JavaBean:
public interface Address {
public String getAddress();
}
public class AddressImpl implements Address {
private String address;
public void setAddress(String address){
this.address = address;
}
@Override
public String getAddress() {
return address;
}
}
public class AddressAdapter extends XmlAdapter<String, Address> {
@Override
public Address unmarshal(String v) throws Exception {
AddressImpl ad = new AddressImpl();
ad.setAddress(v);
return ad;
}
@Override
public String marshal(Address v) throws Exception {
return v.getAddress();
}
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
//@XmlAttribute
private int id;
@XmlJavaTypeAdapter(AddressAdapter.class)
private Address address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
测试类:
@Test
public void testObj() throws Exception{
JAXBContext context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();
AddressImpl ad = new AddressImpl();
ad.setAddress("hangzhou");
Person p = new Person();
p.setAddress(ad);
marshaller.marshal(p, System.out);
}
运行结果:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><person><id>0</id><address>hangzhou</address></person>