Java HTML / XML How to - Serialize HashTable to XML








Question

We would like to know how to serialize HashTable to XML.

Answer

import java.io.StringWriter;
import java.util.Hashtable;
/*w w w  . j a v a 2 s. com*/
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Wrapper.class);
    Wrapper wrapper = new Wrapper();
    Hashtable<String, String> hashtable = new Hashtable<String, String>();
    hashtable.put("foo", "A");
    hashtable.put("bar", "B");
    wrapper.setHashtable(hashtable);
    System.out.println(objectToXml(jc, wrapper));
  }

  public static String objectToXml(JAXBContext jaxbContext, Object object)
      throws JAXBException {
    StringWriter writerTo = new StringWriter();
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(object, writerTo); 
    return writerTo.toString();
  }

  @XmlRootElement
  public static class Wrapper {

    private Hashtable<String, String> hashtable;

    public Hashtable<String, String> getHashtable() {
      return hashtable;
    }

    public void setHashtable(Hashtable<String, String> hashtable) {
      this.hashtable = hashtable;
    }

  }

}