我使用java SDK中的xjc从以下xsd文件创建我的JAXB类:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="customer" type="customer"/>
<xs:complexType name="customer">
<xs:sequence>
<xs:element name="customerinfo" type="information"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="information">
<xs:choice minOccurs="1" maxOccurs="1">
<xs:element name="infos" type="informations"/>
<xs:element name="addressline" type="address"/>
<xs:element name="string" type="xs:string"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="informations">
<xs:choice minOccurs="1" maxOccurs="unbounded">
<xs:element name="infos" type="informations"/>
<xs:element name="addressline" type="address"/>
<xs:element name="string" type="xs:string"/>
</xs:choice>
</xs:complexType>
<xs:complexType name="address"/>
</xs:schema>
正如您所看到的那样,“infos”元素中有一些递归。 当我用xjc创建我的类并按如下方式创建这些类的实例时:
ObjectFactory objFact = new ObjectFactory();
Customer customer = objFact.createCustomer();
Information infoRoot = objFact.createInformation();
Information infoInside = objFact.createInformation();
Information infoInside2 = objFact.createInformation();
Informations infos = objFact.createInformations();
Address addressInside = objFact.createAddress();
infos.getInfosOrAddresslineOrString().add(infoInside);
infos.getInfosOrAddresslineOrString().add(addressInside);
infos.getInfosOrAddresslineOrString().add("bla");
Informations infosInside = objFact.createInformations();
infosInside.getInfosOrAddresslineOrString().add(infoInside2);
infoInside.setInfos(infosInside);
infoRoot.setInfos(infos);
customer.setCustomerinfo(infoRoot);
JAXBElement<Customer> jaxbCustomer = objFact.createCustomer(customer);
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(jaxbCustomer, System.out);
输出并不像我预期的那样:
<customer>
<customerinfo>
<infos>
<addressline xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="information">
<infos>
<addressline xsi:type="information"/>
</infos>
</addressline>
<addressline/>
<string>bla</string>
</infos>
</customerinfo>
</customer>
正如您所看到的,infos对象周围有一个额外的元素,它从未在代码中实例化过。 为什么将这个元素添加到marhsalled xml?