user124478
user124478

Reputation:

jaxb xmlelement marshalling with custom attributes

trying to map my class to xml and add custom attributes.

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

after marshalling to xml looks like something like this:

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

I need to have xml like this:

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

As you can see I added type and defaultValue attributes. How can I add them to myXmlMappings class to be visible after marshalling?

Adding extra fields to myXmlMappings class is not viable I would like to do it somehow with annotations.

Upvotes: 1

Views: 2039

Answers (2)

gsjava
gsjava

Reputation: 131

Try this:


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;
}

Upvotes: 1

bdoughan
bdoughan

Reputation: 149047

XML Representation

I would recommend the following XML representation:

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

Java Model

With the following Java model:

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;
}

Upvotes: 1

Related Questions