如何正确处理JAXB中的继承

时间:2014-10-08 10:07:35

标签: inheritance jaxb abstraction jaxb2 xml-validation

我有一个关于JAXB和继承的问题,有以下要求:

  • XSD首先
  • 我们使用org.jvnet.jaxb2.maven2从xsd生成代码:maven-jaxb2-plugin
  • xml验证应该有效

这是我的基础XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       targetNamespace="http://api.mijathi.be/msg/schema/vehicle"
       xmlns="http://api.mijathi.be/msg/schema/vehicle"
       elementFormDefault="qualified"
       attributeFormDefault="unqualified">

<xs:element name="vehicles">
    <xs:complexType>
        <xs:sequence minOccurs="1" maxOccurs="1">
            <xs:element ref="vehicleType" minOccurs="1" maxOccurs="1"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:element name="vehicleType" type="vehicleType"/>

<xs:complexType name="vehicleType" abstract="true">
    <xs:sequence/>
</xs:complexType>
</xs:schema>

现在实施:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       targetNamespace="http://api.mijathi.be/msg/schema/vehicle"
       xmlns="http://api.mijathi.be/msg/schema/vehicle"
       elementFormDefault="qualified"
       attributeFormDefault="unqualified">

<xs:include schemaLocation="http://api.mijathi.be/msg/schema/vehicle/main.xsd"/>

<xs:element name="car" type="carDescription" substitutionGroup="vehicleType"/>

<xs:complexType name="carDescription">
    <xs:complexContent>
        <xs:extension base="vehicleType">
            <xs:sequence>
                <xs:element name="make" type="xs:string" minOccurs="1" maxOccurs="1"/>
            </xs:sequence>
        </xs:extension>
    </xs:complexContent>

</xs:complexType>
</xs:schema>

类的生成很好。我甚至可以使用这个例子xml:

很好地解组
<veh:vehicles xmlns:veh="http://api.mijathi.be/msg/schema/vehicle">
<veh:vehicleType xsi:type="veh:car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <veh:make>string</veh:make>
</veh:vehicleType>
</veh:vehicles>

但是外部,例如,使用您的IDE,XML的验证当然在这个块上失败了。因为veg命名空间中没有定义“car”:

<veh:vehicleType xsi:type="veh:car" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <veh:make>string</veh:make>
</veh:vehicleType>

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

很少有什么可能有用:

  • 如果您有单独的架构,请考虑使用xs:import而不是xs:include。否则它基本上变成了#34;一个&#34;架构,我不认为这是你的意图。
  • 在XML中使用xsi:schemaLocation,请参阅此处: what is the use of xsi:schemaLocation?
  • 在Eclipse中,您可以在Preferences&gt;中添加XML Schema。 XML目录,例如使用名称空间URI。

要验证,Eclipse需要访问您的架构。怎么知道从哪里得到它?好吧,xsi:schemaLocation或中央目录。