Home >Java >javaTutorial >How to Marshal a Map to a Custom XML Format with Key-Value Elements Using JAXB?

How to Marshal a Map to a Custom XML Format with Key-Value Elements Using JAXB?

DDD
DDDOriginal
2024-11-13 03:38:02313browse

How to Marshal a Map to a Custom XML Format with Key-Value Elements Using JAXB?

Marshalling Maps to Custom XML Format Using JAXB

Question:

How can we marshal a map into a custom XML format, where the key value pairs are represented as value elements?

Discussion:

The default JAXB approach for marshalling a map generates XML with a structure like:

<map>
  <entry>
    <key>KEY</key>
    <value>VALUE</value>
  </entry>
  <entry>
    <key>KEY2</key>
    <value>VALUE2</value>
  </entry>
</map>

However, sometimes we may need the XML to be in a custom format:

<map>
  <key>VALUE</key>
  <key2>VALUE2</key2>
</map>

Solution 1: Restricting XML Contract

This is not recommended as it makes the XML elements dependent on the runtime content of the map, which is undesirable for interface layer usage. Instead, we suggest using an enumerated type as the key for the map.

public enum KeyType {
  KEY,
  KEY2;
}

@XmlJavaTypeAdapter(MapAdapter.class)
Map<KeyType, String> mapProperty;

Solution 2: Simplifying Default Structure

If we wish to simplify the default generated structure to:

<map>
    <item key="KEY" value="VALUE"/>
    <item key="KEY2" value="VALUE2"/>
</map>

We can use a Map adapter that converts the map to an array of MapElements:

class MapElements {
    @XmlAttribute
    public String key;
    @XmlAttribute
    public String value;
    
    ...
}

public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {
    ...
}

The above is the detailed content of How to Marshal a Map to a Custom XML Format with Key-Value Elements Using JAXB?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn