首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带有自定义属性的jaxb xmlelement编组

带有自定义属性的jaxb xmlelement编组
EN

Stack Overflow用户
提问于 2012-08-01 23:14:25
回答 2查看 1.8K关注 0票数 1

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

代码语言:javascript
运行
复制
public class MyXmlMappings  {
    @XmlElement
    protected String username;
    @XmlElement
    protected String password;
    @XmlElement
    protected Integer age;
}

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

代码语言:javascript
运行
复制
<myXmlMappings>
<username/>
<password/>
<age/>
</myXmlMappings>

我需要这样的xml:

代码语言:javascript
运行
复制
<myXmlMappings>
<username type="String" defaultValue="hello" />
<password type="String" defaultValue="asdf" />
<age type="Integer" defaultValue="25" />
</myXmlMappings>

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

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-01 23:44:40

XML表示法

我建议使用以下XML表示法:

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

代码语言:javascript
运行
复制
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class MyXmlMappings  {
    @XmlElement(name="xmlMapping")
    protected List<XmlMapping> xmlMappings;

}

XmlMapping

代码语言:javascript
运行
复制
@XmlAccessorType(XmlAccessType.FIELD)
public class XmlMapping {
    @XmlAttribute
    protected String name;
    @XmlAttribute
    protected String type;
    @XmlAttribute
    protected String defaultValue;
}
票数 1
EN

Stack Overflow用户

发布于 2012-08-01 23:45:53

试试这个:

代码语言:javascript
运行
复制
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;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11762271

复制
相关文章

相似问题

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