2017-01-27 9 views
1

Java.util.Map からXMLを作成したいと考えています。そのマップに値を入れて、ルート要素を構成できるXMLを作成しようとしていて、子要素がそのマップから作成されます。私はJAXBを使用する例を見てきましたが、私は生成しようとしているとして、これらの例では、XMLタグを作成しませんJAXBを使用してMAPからXMLを作成する

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

Map mp = new HashMap(); 

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

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

そして、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> 

答えて

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クラス:XMLを作成することによって、このCustomMap

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

    } 
} 

テストコードを作成し

@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); 
    } 

} 

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> 

私だけだから非整列化部分を実装していませんでしたマーシャリング必要。

関連する問題