簡體   English   中英

XML和JAXB:將屬性傳遞給值

[英]XML & JAXB: pass attribute into value

我有大量通過JAXB( maven-jaxb2-plugin )生成的對象,並使用jaxb2-annotate-plugin 這些類可以定義一個RelationType ,我想用相應的@RelationType注釋@RelationType注釋。 我使用XPath表達式在XSD中找到name屬性並注釋該類,並將其特定類型傳遞到注釋中。 下面是一個示例:

<jaxb:bindings node="//xsd:complexType[@name='SomeRelationType']">
    <annox:annotate target="class">@com.example.RelationType(type = "SomeRelationType")</annox:annotate>
</jaxb:bindings>

對應以下XSD代碼段:

<xsd:complexType name="SomeRelationType">
    <xsd:complexContent>
        <xsd:extension base="RelationType">
            <xsd:sequence>
                <xsd:element name="someValue" type="SomeValue"/>
                <xsd:element name="otherValue" type="OtherValue"/>                     
            </xsd:sequence>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

我找到了在的ComplexType SomeRelationType的名稱,並注釋類@RelationType注解,它具有SomeRelationType作為其類型參數。 它將生成以下類:

@RelationType(type = "SomeRelationType")
public class SomeRelationType extends RelationType implements Serializable {
    private final static long serialVersionUID = 1L;
    protected SomeValue someValue;
    protected OtherValue otherValue;    
}

如果它只是幾個域對象,則效果很好。 但是我的工作量很大,手動定義每個注釋不僅繁瑣,而且在更改和擴展方面也很糟糕。

為了泛化它,我可以將XPath表達式重寫為以下內容:

<jaxb:bindings node="//xsd:complexType[substring(@name, string-length(@name) - string-length('RelationType') + 1)]" multiple="true">
    <annox:annotate target="class">@com.example.RelationType(type = "SomeRelationType")</annox:annotate>
</jaxb:bindings>

問題:我的注釋的type參數仍然定義為"SomeRelationType" 如果我可以使用XPath表達式中定義的@name ,那將是很好的。 然后,所有名稱以"RelationType"結尾的類也將自動獲取帶有正確type參數的@RelationType批注。

當然,它不像執行以下操作那樣簡單,但是它顯示了我想要實現的目標:

<jaxb:bindings node="//xsd:complexType[substring(@name, string-length(@name) - string-length('RelationType') + 1)]" multiple="true">
    <annox:annotate target="class">@com.example.RelationType(type = @name)</annox:annotate>
</jaxb:bindings>

這樣的事情在XML / JAXB中甚至可能嗎?

但是我的工作量很大,手動定義每個注釋不僅繁瑣,而且在更改和擴展方面也很糟糕。

對我來說, @com.example.RelationType(type = "SomeRelationType")看起來像一個簡單的元信息,可以通過反射來導出而無需任何注釋。 因此,請檢查是否有一種方法可以進行“配置之上的約定”。

jaxb2-annotate-plugin不也將不支持參數化,它實現起來太狹窄也太復雜。 免責聲明我是jaxb2-annotate-plugin的作者

我看到兩個選擇:

  • 在生成中預先生成綁定。 XML Schema是XML,因此編寫XSLT來生成綁定文件應該不會太復雜。
  • 編寫自己的XJC插件,根據需要添加注釋。
  • 賄賂我為jaxb2-annotate-plugin添加參數

是的,只有兩個選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM