簡體   English   中英

使用JAXB從MAP創建XML

[英]Using JAXB to create XML from MAP

我想從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標記。

任何人都可以給我一些鏈接或建議嗎? 提前致謝!

我遵循了這些建議: 這個這個

但它生成這個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>

我做的! 使用了這個例子

從上面的帖子:創建這個類:

    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部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM