首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XML & JAXB:将属性传递给值

XML & JAXB:将属性传递给值
EN

Stack Overflow用户
提问于 2016-03-18 10:43:07
回答 1查看 476关注 0票数 0

我有大量通过JAXB (maven-jaxb2-plugin)生成的对象,并使用jaxb2-annotate-plugin对它们进行注释。这些类可以定义一个RelationType,我想用相应的@RelationType注释对它们进行注释。我使用一个XPath表达式来查找XSD中的name属性,并对类进行注释,将其特定类型传递到注释中。这方面的一个例子如下:

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

它映射在以下XSD片段上:

代码语言:javascript
复制
<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作为其类型参数。它将生成以下类:

代码语言:javascript
复制
@RelationType(type = "SomeRelationType")
public class SomeRelationType extends RelationType implements Serializable {
    private final static long serialVersionUID = 1L;
    protected SomeValue someValue;
    protected OtherValue otherValue;    
}

如果它只是几个域对象,这就很好了。但是我有大量的注释,手工定义每个注释不仅乏味,而且在更改和扩展方面也很糟糕。

要泛化它,我可以重写XPath表达式如下:

代码语言:javascript
复制
<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>

问题:我的注释的类型参数仍然被定义为"SomeRelationType"。如果我可以使用在@name表达式中定义的相同的XPath,那就太好了。然后,名称以"RelationType"结尾的所有类也会自动获得带有正确type参数的@RelationType注释。

当然,它并不像执行以下操作那样简单,但它展示了我想要实现的目标:

代码语言:javascript
复制
<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中是可能的还是不可能的?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-19 13:35:57

但是我有大量的注释,手工定义每个注释不仅乏味,而且在更改和扩展方面也很糟糕。

对我来说,@com.example.RelationType(type = "SomeRelationType")看起来就像一种琐碎的方法,可以通过反射导出,无需任何注释。因此,请检查是否有一种方法来做“约定而不是配置”的事情。

jaxb2-annotate-plugin不支持参数化,也不支持参数化,因为它太窄,太复杂,无法实现。免责声明我是jaxb2 2-注释-插件的作者。

我认为有两种选择:

  • 在构建中预生成绑定。XML是XML,因此编写XSLT来生成绑定文件不应该太复杂。
  • 编写自己的XJC插件,根据需要添加注释。
  • 贿赂我为jaxb2 2-注释-插件添加参数化。

好的,只有两个选择。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36082277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档