0

I'm searching an Api to convert List of maps to Xml.

I don't want to use any annotation-based parsers like JaxB. Is there any convenient library to do this?

List<Map<String, Object>> myList = new ArrayList(); 

Map<String,String> map1 = new HashMap<String,String();
map.put("name","mike");
map.put("surname","smith");

Map<String,String> map2 = new HashMap<String,String();
map.put("name","bob");
map.put("surname","smith");

myList.add(map1);
myList.add(map2);

I want to save it to file like this:

<map1>
  <name>mike</name>
  <surname>smith</surname>
</map1>
<map2>
  <name>bob</name>
  <surname>smith</surname>
</map2>
  • 3
    Possible duplicate of [How to convert XML to java.util.Map and vice versa](https://stackoverflow.com/questions/1537207/how-to-convert-xml-to-java-util-map-and-vice-versa) – miljon May 06 '19 at 12:52
  • Possible duplicate of [HashMap to XML syntax](https://stackoverflow.com/questions/25813994/hashmap-to-xml-syntax) – Ronald Haan May 06 '19 at 12:54
  • 1
    Note that you won't get elements like `` and `` because those names aren't available to whatever you use to serialize the list to xml (Jackson could be another way to do it next to what has already been suggested). If you need those element names you'll probably want to use a nested map and do `outerMap.put("map1", map1 )` etc. – Thomas May 06 '19 at 12:56

1 Answers1

0

First point is that it's a rather poor XML design. Giving the maps different names (map1, map2 etc) will almost certainly make it harder to process the XML. But perhaps you don't have any control over the design.

Next point is that to generate this XML from Java, I wouldn't normally choose to start by constructing a list of maps. But again, perhaps you don't have any control over the form of the input.

If you're using Saxon, you can convert each Map to an XdmMap using the static method XdmMap.makeMap(Map); since the XdmMap is an XdmItem you can then construct a sequence of maps as an XdmValue using the constructor XdmValue(Iterable<? extends XdmItem>). You can then pass this XdmValue as a parameter (named say list-of-maps) to a stylesheet that simply does

<xsl:param name="list-of-maps" as="map(xs:string, xs:string)*"/>
<xsl:template name="xsl:initial-template">
  <xsl:for-each select="$list-of-maps">
    <xsl:element name="map{position()}">
      <name>{?name}</name>
      <surname>{?surname}</surname>
    </xsl:element>
  </xsl:for-each>
</xsl:template>
Michael Kay
  • 156,231
  • 11
  • 92
  • 164