6

我正在使用 JAXB 来解析 xml。我有一个如下架构,以及在此架构上定义的两个 xml 文件 a.xml 和 b.xml。a.xml 通过 xi:include xml 标记依赖于 b.xml。请归档以下示例以获得更清晰的数据

 I have followng schema definition:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"  attributeFormDefault="unqualified">
    <xs:element name="Task">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="Details" minOccurs="1" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>
<xs:element name="Details">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="NAme" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>
</xs:schema>

这是两个xml文件:

一个.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Task xmlns:xi="http://www.w3.org/2001/XInclude">
<Details>
    <xi:include href="b.xml"/>
</Details>
</Task>

b.xml:

 <?xml version="1.0" encoding="UTF-8"?>
 <Detail>
  <Name>Name1</Name>
 </Detail>
<Detail>
   <Name>Name2</Name>
 </Detail>

现在我使用 JAXB SAXFactory 将其解析为:

 JAXBContext jaxbcon = JAXBContext.newInstance("schema-definition-jaxb-files");
 unmar = jaxbcon.createUnmarshaller();

 SAXParserFactory spf = SAXParserFactory.newInstance();
 spf.setXIncludeAware(true);
 XMLReader xr = spf.newSAXParser().getXMLReader();
 SAXSource source = new SAXSource(xr, new InputSource(new    FileInputStream(xmlfilename)));
 Object obj = unmar.unmarshal(source);

解析成功,但Details JAXB 标记对象为空。无论如何,a.xml 文件中的 xi:include 标记没有被展平。任何想法?

4

2 回答 2

4

试试这个,它肯定有效:

public class Test {
    public String include;

    public static void main(String[] args) throws Exception {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setXIncludeAware(true);
        spf.setNamespaceAware(true);
        XMLReader xr = spf.newSAXParser().getXMLReader();
        SAXSource src = new SAXSource(xr, new InputSource("test.xml"));
        Test t = JAXB.unmarshal(src, Test.class);
        System.out.println(t.include);
    }
}
于 2012-11-20T00:26:49.660 回答
2

你应该添加

    spf.setNamespaceAware(true);
于 2012-11-20T00:23:35.160 回答