我正在使用 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 对象周围有一个额外的元素,该元素从未在代码中实例化。为什么将此元素添加到编组的 xml 中?