使用JAXB从MAP创建XML

时间:2017-01-27 12:22:14

标签: java xml jaxb

我想从Java.util.Map创建XML 我将值放在该映射中并尝试创建XML,其中根元素将是可配置的,并且将从该映射创建子元素。

 Map mp = new HashMap(); 

  mp.put("key","shaon"):

  mp.put("newKey","newValue");

XML就像:

<shaonsXML>
  <key>shaon</key>
  <newKey> newValue </newKey>
</shaonsXML>

我见过使用JAXB的示例,但是这些示例并没有像我想要生成的那样创建XML标记。

任何人都可以给我一些链接或建议吗?提前谢谢!

我已遵循以下建议:thisthis

但是它生成了这个XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
    <mapProperty>
        <item>
            <key>KEY1</key>
            <value>SHAON</value>
        </item>
        <item>
            <key>newKEY</key>
            <value>newValue</value>
        </item>
    </mapProperty>
</root>

1 个答案:

答案 0 :(得分:0)

我做到了!使用this示例

从上面的帖子:创建这个类:

    public class MapAdapter extends XmlAdapter<MapWrapper, Map<String, String>>{

    @Override
    public Map<String, String> unmarshal(MapWrapper v) throws Exception {
        Map<String, String> map = new HashMap<String,String>();//v.toMap();

        return map;
    }

    @Override
    public MapWrapper marshal(Map<String, String> m) throws Exception {
        MapWrapper wrapper = new MapWrapper();

        for(Map.Entry<String, String> entry : m.entrySet()){
             wrapper.addEntry(new JAXBElement<String>(new QName(entry.getKey()), String.class, entry.getValue()));
        }

        return wrapper;
    }

}

MapWrapper类:

@XmlType
public class MapWrapper{
    private List<JAXBElement<String>> properties = new ArrayList<>();

    public MapWrapper(){

    }

    @XmlAnyElement
    public List<JAXBElement<String>> getProperties() {
        return properties;
    }
    public void setProperties(List<JAXBElement<String>> properties) {
        this.properties = properties;
    }
    public void addEntry(JAXBElement<String> prop){
        properties.add(prop);
    }

    public void addEntry(String key, String value){
        JAXBElement<String> prop = new JAXBElement<String>(new QName(key), String.class, value);
        addEntry(prop);
    }

}

创建此CustomMap

@XmlRootElement(name="RootTag")
public class CustomMap extends MapWrapper{
    public CustomMap(){

    }
}

通过创建XML来测试代码:

private static void writeAsXml(Object o, Writer writer) throws Exception
  {
    JAXBContext jaxb = JAXBContext.newInstance(o.getClass());

    Marshaller xmlConverter = jaxb.createMarshaller();
    xmlConverter.setProperty("jaxb.formatted.output", true);
    xmlConverter.marshal(o, writer);
  }


CustomMap map = new CustomMap();
    map.addEntry("Key1","Value1");
    map.addEntry("Key2","Value2");
    map.addEntry("Key3","Value3");
    map.addEntry("Key4","Value4");
    writeAsXml(map, new PrintWriter(System.out));

制作XML:

<RootTag>
    <Key1>Value1</Key1>
    <Key2>Value2</Key2>
    <Key3>Value3</Key3>
    <Key4>Value4</Key4>
</RootTag>

我只需要Marshaling所以没有实现Unmarshal部分。