Home >Java >javaTutorial >How to Marshal a Map into `value` Format in JAXB?
JAXB natively supports marshalling a Map into a structure like this:
<map> <entry> <key> KEY </key> <value> VALUE </value> </entry> <entry> <key> KEY2 </key> <value> VALUE2 </value> </entry> ... </map>
However, in certain cases, it might be necessary to generate XML where the key becomes an element name and the value becomes its content, like so:
<map> <key> VALUE </key> <key2> VALUE2 </key2> ... </map>
It's generally advisable to avoid this type of XML generation because it introduces dependency on the map's content at runtime. This can impact interface contracts defined in the XML Schema (XSD).
Instead, consider using an enumerated type as the key of the Map to ensure that element names are known at compile time, allowing JAXB to generate a schema that restricts elements in the XML.
To simplify the default generated structure to something like:
<map> <item key="KEY" value="VALUE"/> <item key="KEY2" value="VALUE2"/> </map>
Implement a custom MapAdapter that converts the Map into an array of MapElements.
The above is the detailed content of How to Marshal a Map into `value` Format in JAXB?. For more information, please follow other related articles on the PHP Chinese website!