0

I have to production something like this:

<Doc p1="something">
    <Ext code="one"/>
    <Ext name="two"/>
</Doc>

I know how to do the part with my Doc class, the "code" and "name" are just properties of the Doc, so I was going to create a wrapper class Ext to produce that element, but I'm not sure how to use "code" as the attribute in one case and "name" as the attribute in another case. I could always create two different wrapper classes I suppose, but I was wondering if there was an easier way, such as some way to set what the @XmlAttribute(name=) will be with a variable somehow.

Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106

2 Answers2

1

You can't do what you're trying to do - as LINEMAN78 said, variable attribute names do not a valid XSD make. If you know what your list of candidate attributes consists of (e.g. your Exts can have Code, Name, Foo, Bar, and Baz), you can just use @XmlAttributes to define them; by default an XmlAttribute is not required and, if the Java object value is null, will not show up in the marshalled output.

Sbodd
  • 11,279
  • 6
  • 41
  • 42
  • Only downside is that it is still valid to specify none or all of the attributes so there is no inherit validation. – LINEMAN78 Nov 02 '13 at 23:57
0

Variable attribute names are not valid for an xml schema definition, but you can do a choice for an element, so it would be:

<Doc p1="something">
    <Code>one</Code>
    <Name>two</Name>
</Doc>

To do this you would use a JaxbElement and it wouldn't require a wrapper class. The xsd would look like this:

<complexType name="Doc">
    <sequence>
        <choice maxOccurs="unbounded">
            <element name="Code" type="string" />
            <element name="Name" type="string" />
        </choice>
    </sequence>
    <attribute name="p1" type="string" />
</complexType>

Which would result in the following code:

@XmlElementRefs({
    @XmlElementRef(name = "Code", type = JAXBElement.class, required = false),
    @XmlElementRef(name = "Name", type = JAXBElement.class, required = false)
})
protected List<JAXBElement<String>> codeOrName;

Where JaxbElement is used like this:

new JAXBElement<String>(new QName( "", "Name" ), String.class, Doc.class, value);
LINEMAN78
  • 2,562
  • 16
  • 19