public abstract class Base {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
// parent 클래스에 설정
@XmlTransient
public class Person extends Base {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@XmlRootElement
@XmlType(propOrder = {"name", "phoneNumbers", "password"})
public class Customer extends Person {
private String password;
private List phoneNumbers;
@XmlElement(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@XmlElement(name = "phone-number")
public List getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}
public class XmlTest {
@Test
public void jaxbTest() throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File(Customer.class.getProtectionDomain().getCodeSource().getLocation().getPath()+"/jaxb/input.xml");
Customer customer = (Customer) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
}
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<id>123</id>
<name>Jane Doe</name>
<phone-number>555-1111</phone-number>
<phone-number>555-2222</phone-number>
<password>1234</password>
</customer>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<id>123</id>
<name>Jane Doe</name>
<phone-number>555-1111</phone-number>
<phone-number>555-2222</phone-number>
<password>1234</password>
</customer>
public class XmlTest {
@Test
public void jaxbTest2() throws Exception {
Customer cus = new Customer();
cus.setId(123);
cus.setName("Dennis");
cus.setPassword("1234");
ArrayList phoneNumbers = new ArrayList();
phoneNumbers.add("555-1111");
phoneNumbers.add("555-2222");
cus.setPhoneNumbers(phoneNumbers);
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(cus, System.out);
}
}
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<id>123</id>
<name>Dennis</name>
<phone-number>555-1111</phone-number>
<phone-number>555-2222</phone-number>
<password>1234</password>
</customer>
댓글 없음:
댓글 쓰기