JAXB unmarshall and embedded XSD

2019-02-27 10:01发布

问题:

I have an XML who embed the XSD, so it's something like :

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
      <xs:complexType>
        <xs:choice minOccurs="0" maxOccurs="unbounded">
          <xs:element name="Table">
            <xs:complexType>
              <xs:sequence>
                <xs:element name="elem1" type="xs:string" minOccurs="0" />
                <xs:element name="elem2" type="xs:string" minOccurs="0" />
                <xs:element name="elem3" type="xs:string" minOccurs="0" />
                <xs:element name="elem4" type="xs:string" minOccurs="0" />
                <xs:element name="elem5" type="xs:string" minOccurs="0" />
              </xs:sequence>
            </xs:complexType>
          </xs:element>
        </xs:choice>
      </xs:complexType>
    </xs:element>
  </xs:schema>
  <Table>
    <elem1>random1</elem1>
    <elem2/>
    <elem3>random3</elem3>
    <elem4>random4</elem4>
    <elem5>random5</elem5>
  </Table>
</NewDataSet>

I'm currently using the a clone of the embedded XSD as Schema :

<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
  <xs:complexType>
    <xs:choice minOccurs="0" maxOccurs="unbounded">
      <xs:element name="Table">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="elem1" type="xs:string" minOccurs="0" />
            <xs:element name="elem2" type="xs:string" minOccurs="0" />
            <xs:element name="elem3" type="xs:string" minOccurs="0" />
            <xs:element name="elem4" type="xs:string" minOccurs="0" />
            <xs:element name="elem5" type="xs:string" minOccurs="0" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:choice>
  </xs:complexType>
</xs:element>

But the problem is that, when i want to unmarshal an entry XML I get the following error message :

unexpected element (uri:"http://www.w3.org/2001/XMLSchema", local:"schema"). Expected elements are <{}Table>

I tried to add the tag on my XSD but without success, still get an error because of the namespace (i guess ?).
Any help and explanations would be really appreciate.

回答1:

You can leverage a StAX StreamFilter on an XMLStreamReader so that the elements corresponding to the XML schema are not reported as events. Then you can unmarshal from the XMLStreamReader with JAXB.

  • JAXB filtered parsing