我正在使用JAXB,无法弄清楚为什么我的嵌套对象没有被解组。我通过XJC命令生成类。
例如,当我解组Works对象时,Composers集合始终包含一个Composer实例将为NULL名称。
我的XML看起来像这样:
<Works>
<Work>
<Composer>
<Name>Test Name</Name>
</Composer>
</Work>
</Works>
和XSD是这样的:
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
jxb:version="2.0" xmlns:tns="http://www.example.org/test/"
targetNamespace="http://www.example.org/test/">
<element name="Works" type="tns:Work"></element>
<complexType name="Work">
<sequence>
<element name="Composers" type="tns:Composer" maxOccurs="unbounded"
minOccurs="1">
</element>
</sequence>
</complexType>
<complexType name="Composer">
<sequence>
<element name="Name" type="string">
</element>
</sequence>
</complexType>
我的代码解组:
JAXBContext jc = JAXBContext.newInstance("mypackagename");
Unmarshaller um = jc.createUnmarshaller();
Works works = (Works)um.unmarshal(new FileReader("src/main/resources/works.xml"));
Work work = works.getWorks().get(0);
Composer composer = work.getComposers().get(0);
System.out.println(composer.getName());
名称始终为NULL,即使我知道它有值。
答案 0 :(得分:3)
您可以使用以下XML架构:
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
jxb:version="2.0" xmlns:tns="http://www.example.org/test/"
targetNamespace="http://www.example.org/test/">
<element name="Works" type="tns:Works"></element>
<complexType name="Works">
<sequence>
<element name="Work" type="tns:Work" maxOccurs="unbounded"/>
</sequence>
</complexType>
<complexType name="Work">
<sequence>
<element name="Composer" type="tns:Composer" maxOccurs="unbounded"/>
</sequence>
</complexType>
<complexType name="Composer">
<sequence>
<element name="Name" type="string"/>
</sequence>
</complexType>
</schema>
这对应于以下XML:
<Works xmlns="http://www.example.org/test/">
<Work>
<Composer>
<Name>Test Name</Name>
</Composer>
</Work>
</Works>