fork download
  1. import javax.xml.bind.*;
  2. import javax.xml.bind.annotation.*;
  3. import javax.xml.bind.annotation.adapters.*;
  4. import java.io.*;
  5. import java.util.*;
  6.  
  7. @XmlRootElement(name="myroot")
  8. @XmlAccessorType(XmlAccessType.NONE)
  9. class SO19509130a {
  10.  
  11. private String id;
  12. private Properties props = new Properties();
  13.  
  14. @XmlAttribute public String getId() { return id; }
  15. public void setId(String id) { this.id = id; }
  16.  
  17. @XmlElement
  18. @XmlJavaTypeAdapter(SO19509130a.PropertiesAdapter.class)
  19. public Properties getProperties() { return props; }
  20. public void setProperties(Properties props) { this.props.putAll(props); }
  21.  
  22. @XmlType(name="property") static class XmlProperty {
  23. @XmlAttribute public String key;
  24. @XmlValue public String value;
  25. }
  26.  
  27. @XmlType(name="properties") static class XmlProperties {
  28. @XmlElement(name="entry") public Collection<XmlProperty> entries
  29. = new ArrayList<XmlProperty>();
  30. }
  31.  
  32. static class PropertiesAdapter
  33. extends XmlAdapter<XmlProperties, Properties>
  34. {
  35. public XmlProperties marshal(Properties props) {
  36. XmlProperties xml = new XmlProperties();
  37. for (Map.Entry<Object, Object> entry: props.entrySet()) {
  38. XmlProperty xmlEntry = new XmlProperty();
  39. xmlEntry.key = entry.getKey().toString();
  40. xmlEntry.value = entry.getValue().toString();
  41. xml.entries.add(xmlEntry);
  42. }
  43. return xml;
  44. }
  45. public Properties unmarshal(XmlProperties xml) {
  46. Properties props = new Properties();
  47. for (XmlProperty entry: xml.entries)
  48. props.setProperty(entry.key, entry.value);
  49. return props;
  50. }
  51. }
  52.  
  53. public static void main(String[] args) throws Exception {
  54. SO19509130a obj = new SO19509130a();
  55. obj.id = "theID";
  56. obj.props.setProperty("key1", "val1");
  57. obj.props.setProperty("key2", "val2");
  58. JAXBContext ctx = JAXBContext.newInstance(SO19509130a.class);
  59. Marshaller m = ctx.createMarshaller();
  60. Unmarshaller u = ctx.createUnmarshaller();
  61. m.marshal(obj, baos);
  62. InputStream bais = new ByteArrayInputStream(baos.toByteArray());
  63. obj = (SO19509130a)u.unmarshal(bais);
  64. m.marshal(obj, System.out);
  65. System.out.println();
  66. }
  67. }
  68.  
Success #stdin #stdout 0.24s 381824KB
stdin
Standard input is empty
stdout
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><myroot id="theID"><properties><entry key="key2">val2</entry><entry key="key1">val1</entry></properties></myroot>