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
Release: 2024-11-13 03:38:02
Original
312 people have browsed it

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>
Copy after login

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

<map>
  <key>VALUE</key>
  <key2>VALUE2</key2>
</map>
Copy after login

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;
Copy after login

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>
Copy after login

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>> {
    ...
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template