Code, JavaEE

Transform Map to XML Using JDOM

Here is a nice way to transform a map to xml format.

 


public class XmlTest {

@Test
 public void testStreamHashMapToXml() {
 Map<String, Object> m = new LinkedHashMap<>();
 m.put("Key1","Val");
 m.put("Key2","Val");
 m.put("Key3","Val");
 m.put("Key4","Val");
 m.put("Key5","Val");

Element dataElement = new Element("data");

Iterator iterator = m.entrySet().iterator();
 while(iterator.hasNext()) {
 Map.Entry entry = (Map.Entry)iterator.next();
 String key = (String) entry.getKey();
 Object val = entry.getValue();

dataElement.addContent(new Element(key).setText(val.toString()));
 }

XMLOutputter xmlOut = new XMLOutputter();
 xmlOut.setFormat(Format.getPrettyFormat());
 try {
 xmlOut.output(dataElement, new FileWriter("C:\\tmp\\test.xml"));
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
}

 

It produces an XML file such that:


<data>
 <Key1>Val</Key1>
 <Key2>Val</Key2>
 <Key3>Val</Key3>
 <Key4>Val</Key4>
 <Key5>Val</Key5>
</data>

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s