I’d like to marshall/unmarshall a Map into attributes of an XML element. I’ve seen examples like:
<map>
<entry key="key1">value1</entry>
<entry key="key2">value2</entry>
</map>
What I really want is:
<map key1="value1" key2="value2"/>
Assume with me that there are no complex values and that they can legally be represented as XML attributes. Also, I’m trying to write this generically because the set of keys is not known until runtime.
How would I go about this? I’m familiar with XmlJavaTypeAdapter.
I thought about creating a MyMap that contains a List of entries but this wouldn’t get the output I’d like.
Like I hinted in my comment, this cannot be achieved with JAXB alone. In the JAXB specification (JSR 222) it says:
That means that the scope of the binding is the same as the scope of the schema, which is static. A JAXB binding is not meant to be changed without recompiling the code. There are some exceptions, e.g. for
xs:anyAttributewhich is discussed in section 6.9 of the specification, but since you didn’t vote for the answer suggesting the use of@XmlAnyAttributeyou probably don’t want to live with the limitations – e.g. only haveQNamekeys in your map.I hope you are convinced that to do what you want with JAXB is a really bad idea, but just for reference below is an example that modifies the document after marshalling to bring it to the structure you want. You can copy and paste it into a single file and compile it with Java 7. The output will look like this:
My code only shows the marshalilng the other direction is equivalent: