【问题标题】:jaxb xmlelement marshalling with custom attributes具有自定义属性的 jaxb xmlelement 编组
【发布时间】:2012-08-01 15:14:25
【问题描述】:

尝试将我的类映射到 xml 并添加自定义属性。

public class MyXmlMappings  {
    @XmlElement
    protected String username;
    @XmlElement
    protected String password;
    @XmlElement
    protected Integer age;
}

编组到 xml 后看起来像这样:

<myXmlMappings>
<username/>
<password/>
<age/>
</myXmlMappings>

我需要这样的xml:

<myXmlMappings>
<username type="String" defaultValue="hello" />
<password type="String" defaultValue="asdf" />
<age type="Integer" defaultValue="25" />
</myXmlMappings>

如您所见,我添加了 type 和 defaultValue 属性。如何将它们添加到 myXmlMappings 类以在编组后可见?

向 myXmlMappings 类添加额外字段是不可行的,我想通过注释以某种方式做到这一点。

【问题讨论】:

  • 默认值从何而来?

标签: java jaxb


【解决方案1】:

XML 表示

我会推荐以下 XML 表示:

<myXmlMappings>
    <xmlMapping name="username" type="String" defaultValue="hello" />
    <xmlMapping name="password" type="String" defaultValue="asdf" />
    <xmlMapping name="age" type="Integer" defaultValue="25" />
</myXmlMappings>

Java 模型

使用以下 Java 模型:

XmlMappings

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class MyXmlMappings  {
    @XmlElement(name="xmlMapping")
    protected List<XmlMapping> xmlMappings;

}

XmlMapping

@XmlAccessorType(XmlAccessType.FIELD)
public class XmlMapping {
    @XmlAttribute
    protected String name;
    @XmlAttribute
    protected String type;
    @XmlAttribute
    protected String defaultValue;
}

【讨论】:

    【解决方案2】:

    试试这个:

    
    public class MyXmlMappings {
    
        @XmlPath("username/@type")
        protected String userType;
        @XmlPath("password/@type")
        protected String passwordType;
        @XmlPath("age/@type")
        protected String ageType;
        @XmlPath("username/@defaultValue")
        protected String userDefaultValue;
        @XmlPath("password/@defaultValue")
        protected String passwordDefaultValue;
        @XmlPath("age/@defaultValue")
        protected Integer ageDefaultValue;
        @XmlElement
        protected String username;
        @XmlElement
        protected String password;
        @XmlElement
        protected Integer age;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 2011-11-28
    相关资源
    最近更新 更多