JAVA 实体类Person.java
public class Person { private int id; private String username; private String age; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } //无参构造函数 public Person(){ super(); } //有参构造函数 public Person(int id,String username,String age,String address){ this.id=id; this.username=username; this.age=age; this.address=address; } }
第二个JAVA实体类,把上面声明的Person 实体作为一个变量存在
注意 @XmlRootElement 的注解的使用
import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class ObjectDemo { private String name; private String sex; private Person person; /** * @return the person */ public Person getPerson() { return person; } /** * @param person the person to set */ public void setPerson(Person person) { this.person = person; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the sex */ public String getSex() { return sex; } /** * @param sex the sex to set */ public void setSex(String sex) { this.sex = sex; } //有参构造方法 public ObjectDemo(String name,String sex,Person person){ this.name=name; this.sex=sex; this.person=person; } //无参构造方法 public ObjectDemo(){ super(); } }
测试方法
import java.io.StringReader; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.junit.Test; import com.demo.vo.ObjectDemo; import com.demo.vo.Person; public class XmlToObject { @Test public void XMLTobean() { Person p = new Person(1,"小红","10","北京"); ObjectDemo ob = new ObjectDemo("小明","11",p); try { JAXBContext context = JAXBContext.newInstance(ObjectDemo.class); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(ob,System.out); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Test public void beanToXML() { String xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<objectDemo>" + "<name>小明</name>" + "<person>" + "<address>北京</address>" + "<age>10</age>" + "<id>1</id>" + "<username>小红</username>" + "</person>" + "<sex>11</sex>" + "</objectDemo>"; try { JAXBContext context = JAXBContext.newInstance(ObjectDemo.class); Unmarshaller unmarshaller = context.createUnmarshaller(); ObjectDemo obj = (ObjectDemo)unmarshaller.unmarshal(new StringReader(xml)); System.out.println(obj.getName()); System.out.println(obj.getPerson().getAddress()); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }