2011-06-06 60 views
3

我有一個包含一個HashMap一個簡單的類:JAXB命名空間java.util.Map性質

@XmlRootElement() 
public class Customer { 

    private long id; 
    private String name; 

    private Map<String, String> attributes; 

    public Map<String, String> getAttributes() { 
     return attributes; 
    } 

    public void setAttributes(Map<String, String> attributes) { 
     this.attributes = attributes; 
    } 

    @XmlAttribute 
    public long getId() { 
     return id; 
    } 

    public void setId(long id) { 
     this.id = id; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public static void main(String[] args) throws Exception { 
     JAXBContext jc = 
      JAXBContext.newInstance("com.rbccm.dbos.payments.dao.test"); 

     Customer customer = new Customer(); 
     customer.setId(123); 
     customer.setName("Jane Doe"); 

     HashMap<String, String> attributes = new HashMap<String, String>(); 
     attributes.put("a1", "v1"); 
     customer.setAttributes(attributes); 


     StringWriter sw = new StringWriter(); 
     Marshaller m = jc.createMarshaller(); 
     m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); 
     m.marshal(customer, sw); 
     System.out.println(sw.toString()); 

    } 

} 

Main方法產生以下XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<ns2:customer id="123" xmlns:ns2="http://www.example.org/package"> 
    <ns2:attributes> 
     <entry> 
      <key>a1</key> 
      <value>v1</value> 
     </entry> 
    </ns2:attributes> 
    <ns2:name>Jane Doe</ns2:name> 
</ns2:customer> 

我的問題是輸出哈希映射時會刪除名稱空間。我想生成XML是這樣的:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<ns2:customer id="123" xmlns:ns2="http://www.example.org/package"> 
    <ns2:attributes> 
     <ns2:entry> 
      <ns2:key>a1</ns2:key> 
      <ns2:value>v1</ns2:value> 
     </ns2:entry> 
    </ns2:attributes> 
    <ns2:name>Jane Doe</ns2:name> 
</ns2:customer> 

回答

0

你可以使用一個XmlAdapter與您java.util.Map屬性來獲取您正在尋找的命名空間的資格。

對於使用XmlAdapterjava.uti.Map的例子請參閱:

有關JAXB和命名空間的詳細信息:


FYI

我正在考慮增加一個擴展EclipseLink JAXB (MOXy),以更好地處理這種情況:

@XmlMap(wrapper="my-entry", key="@my-key", value="my-value") 
public Map<String, PhoneNumber> phoneNumbers = new HashMap<String, PhoneNumber>(); 

上述註釋將對應於以下XML:

<phoneNumbers> 
    <my-entry my-key="work"> 
     <my-value>613-555-1111</value> 
    </my-entry> 
</phoneNumbers> 

鍵/值屬性將是XPath語句,並且命名空間信息將遵循什麼其他莫西擴展完成(有關示例見下面的鏈接):

改進請求

+0

沒錯,就是工作。但看起來你必須爲每個你想用作hashmap中的值的類型創建3個額外的類。有了這種開銷,它可能更適合在地圖元素上沒有命名空間。 (其他鏈接非常有幫助,您可能已經注意到我的問題是基於該示例的99%) – Heathen 2011-06-07 10:40:10

+0

該擴展看起來非常有用。 schemagen任務也可以使用它嗎? – Heathen 2011-06-08 08:55:19

+0

@Heathen - 當我們添加它時,它肯定會使用'JAXBContext.genertateSchema()'方法(http://wiki.eclipse.org/EclipseLink/Examples/MOXy/JAXB/GenerateSchema)。我們有另一個增加ant架構生成任務的增強請求(https://bugs.eclipse.org/336076)。 – 2011-06-08 09:02:08