我有一个包含哈希图的简单类:
@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>
你可以使用XmlAdapter http://download.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html与你java.util.Map
属性来获取您正在寻找的命名空间资格。
举个使用的例子XmlAdapter
with java.uti.Map
see:
- http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html http://bdoughan.blogspot.com/2010/07/xmladapter-jaxbs-secret-weapon.html
有关 JAXB 和命名空间的更多信息:
- http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html http://bdoughan.blogspot.com/2010/08/jaxb-namespaces.html
FYI
我正在考虑添加一个扩展EclipseLink JAXB (MOXy) http://www.eclipse.org/eclipselink/moxy.php为了更好地处理这种情况:
@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 扩展的操作(有关示例,请参阅下面的链接):
- http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html http://bdoughan.blogspot.com/2010/09/xpath-based-mapping-geocode-example.html
高级请求
- https://bugs.eclipse.org/322423 https://bugs.eclipse.org/322423
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)