java.util.Map属性的Jaxb名称空间

时间:2011-06-06 16:53:10

标签: java jaxb jaxb2

我有一个包含hashmap的简单类:

@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>

我遇到的问题是在输出hashmap时会删除命名空间。我想生成的是像这样的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>

1 个答案:

答案 0 :(得分:0)

您可以使用XmlAdapterjava.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语句,命名空间信息将遵循为其他MOXy扩展所做的操作(例如,请参见下面的链接):

增强请求