简体   繁体   中英

How to convert List of maps to xml

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>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM