2016-08-25 76 views
0

使用此(演示)模式,我生成Java与JAXB对象:如何使用XmlAdapter将XML复杂类型映射到模式生成类中的Java对象?

<xsd:complexType name="someType"> 
    <xsd:sequence> 
     <xsd:element name="myOtherType" type="otherType" maxOccurs="unbounded" /> 
    </xsd:sequence> 
</xsd:complexType> 

<xsd:complexType name="otherType"> 
    <!-- ... --> 
</xsd:complexType> 

该类获取生成:

@XmlType 
public class SomeType { 

    @XmlElement(name = "myOtherType") 
    OtherType myOtherType; 

} 

但我想用的接口,而不是实现在我JAXB-生成的对象。

所以我写这篇文章的界面:

public interface OtherTypeInterface { 
    // .... 
} 

,我让生成的OTHERTYPE类实现它,有约束力的文件的帮助:

<jxb:bindings node="//xs:complexType[@name='otherType']"> 
    <inheritance:implements>com.example.OtherTypeInterface</inheritance:implements> 
</jxb:bindings> 

到目前为止,一切都很好:

public class OtherType implements OtherTypeInterface { 

    // ... 

} 

但我需要SomeType对象来使用此接口,而不是OtherType实现。建议in the unofficial JAXB guide部分3.2.2。使用@XmlJavaTypeAdapter,我想用自制的XML适配器映射OTHERTYPE其接口,反之亦然:

public class HcpartyTypeAdapter extends XmlAdapter<OtherType, OtherTypeInterface> { 

    @Override 
    public OtherTypeInterface unmarshal(OtherType v) throws Exception { 
     return v; 
    } 

    @Override 
    public OtherType marshal(OtherTypeInterface v) throws Exception { 
     return (OtherType) v; 
    } 

} 

但它看起来像我的绑定文件具有以下配置对应的XML复杂类型是一个很大的禁忌:

<jxb:globalBindings> 
    <xjc:javaType name="com.example.OtherTypeInterface" xmlType="ex:otherType" adapter="com.example.OtherTypeAdapter"/> 
</jxb:globalBindings> 

生成失败,此错误:

com.sun.istack.SAXParseException2; systemId: file:/.../bindings.xjb; lineNumber: 8; columnNumber: 22; undefined simple type "{ http://www.example.com }otherType".

随着a bit of googling,我发现我t显然不可能将XML适配器用于模式生成的类中的复杂类型。但是,如果我手动编辑的文件,用我的转接器,它完美的作品:

public class SomeType { 

    @XmlElement(name = "myOtherType") 
    @XmlJavaTypeAdapter(OtherTypeAdapter.class) 
    @XmlSchemaType(name = "otherType") 
    OtherTypeInterface myOtherType; 

} 

我可以元帅和完美解组它;但在我看来,编辑生成的类会破坏自动处理的整个目的。我正在处理定义许多类型的多个模式。

所以我的问题是:有没有人知道使用XML适配器将XML复杂类型映射到模式生成的类中的Java对象的解决方法,而无需手动编辑代码?


可能的答案在这里:https://stackoverflow.com/a/1889584/946800。我希望自2009年以来,有人可能已经找到某种方法来解决此问题...

回答

0

您可以使用 maven插件为生成的JAXB类添加注释。

  <plugin> 
       <!-- this plugin is used to add annotation for the models --> 
       <groupId>org.jvnet.jaxb2_commons</groupId> 
       <artifactId>jaxb2-basics-annotate</artifactId> 
       <version>1.0.2</version> 
      </plugin> 

.xjb绑定,

<jxb:bindings schemaLocation="sample.xsd"> 
    <jxb:bindings node="//xs:complexType[@name='otherType']"> 
     <annox:annotate target="field"> 
      <annox:annotate annox:class="@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter" 
       value="com.example.OtherTypeAdapter.class" /> 
     </annox:annotate> 
    </jxb:bindings> 
</jxb:bindings> 
相关问题