我有一个名为 联系人 的基本抽象类和两个名为 电话 和 <的子类em>地址 ,它扩展了基类 联系 。
还有另一个名为 客户 的模型,其中包含 联系
类型的属性Contact.java
package test;
import javax.xml.bind.annotation.XmlSeeAlso;
@XmlSeeAlso({Address.class, Phone.class})
public abstract class Contact {
}
Phone.java
package test;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Phone extends Contact {
private String number;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
Address.java
package test;
public class Address extends Contact{
private String name;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Customer.java
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
@XmlElement(name="contact")
private Contact contact1;
public Contact getContact1() {
return contact1;
}
public void setContact1(Contact contact) {
this.contact1 = contact;
}
@XmlElement(name="contact")
private Contact contact;
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
}
情况是,当我尝试编组客户模型时,我得到了预期的xml层次结构,如下所示
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer>
<contact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="phone">
<number>12345</number>
</contact>
<contact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="address">
<city>New York</city>
</contact>
</customer>
JAXB能够找到Customer模型属性的类型(contact和contact1作为Address和Phone),并且已经生成了xml。
但是当我尝试整理模型手机时,生成的输出不会被视为父模型联系
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<phone>
<number>12345</number>
</phone>
我原以为输出xml会有一个Contact模型元素,因为它是父元素。
这是我用于编组的代码
package test;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
Customer customer = new Customer();
Address address1 = new Address();
address1.setCity("New York");
customer.setContact(address1);
Phone p = new Phone();
p.setNumber("12345");
customer.setContact1(p);
JAXBContext jc = JAXBContext.newInstance(Customer.class, Contact.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(customer, System.out);
marshaller.marshal(p, System.out);
}
}
请有人让我了解如何获得预期的xml输出。