JAXB中不使用annotation的示例
程序员文章站
2022-03-20 17:47:26
...
在JAXB中,其实不用annotation也是可以的,虽然比较麻烦,下面是一个例子:
另外一个POJO
然后下面的是一个XML文件,先展示的是将xml文件反序列化为CUSTOMER类,
主程序如下:
可以看到在Customer customer = je1.getValue();
这句之前,就是读入了xml文件,然后进行unmarshaller的操作,之后得到的是一个
JAXBElement的对象实例,然后通过getValue得到其Customer对象实例。然后
接下来的代码是将customer再重新序列化为xml了。
package blog.defaults;
import java.util.List;
public class Customer {
private String firstName;
private String lastName;
private List<PhoneNumber> phoneNumbers;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<PhoneNumber> getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(List<PhoneNumber> phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
}
另外一个POJO
package blog.defaults;
public class PhoneNumber {
private String foo;
private String bar;
public String getType() {
return foo;
}
public void setType(String type) {
this.foo = type;
}
public String getNumber() {
return bar;
}
public void setNumber(String number) {
this.bar = number;
}
}
然后下面的是一个XML文件,先展示的是将xml文件反序列化为CUSTOMER类,
<?xml version="1.0" encoding="UTF-8"?>
<customer>
<firstName>Jane</firstName>
<lastName>Doe</lastName>
<phoneNumbers>
<number>555-1111</number>
<type>work</type>
</phoneNumbers>
<phoneNumbers>
<number>555-2222</number>
<type>home</type>
</phoneNumbers>
</customer>
主程序如下:
package blog.defaults;
import javax.xml.bind.*;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
StreamSource xml = new StreamSource("src/blog/defaults/input.xml");
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<Customer> je1 = unmarshaller.unmarshal(xml, Customer.class);
Customer customer = je1.getValue();
JAXBElement<Customer> je2 = new JAXBElement<Customer>(new QName("customer"), Customer.class, customer);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(je2, System.out);
}
}
可以看到在Customer customer = je1.getValue();
这句之前,就是读入了xml文件,然后进行unmarshaller的操作,之后得到的是一个
JAXBElement的对象实例,然后通过getValue得到其Customer对象实例。然后
接下来的代码是将customer再重新序列化为xml了。