[英]JAXB unmarshaling with namespaces, but without prefix
我想使用JAXB
這是原始的XML:
<customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://example.com">
<dataList>
<data xsi:type="keyValuePair">
<key>key1</key>
<value>val1</value>
</data>
<data xsi:type="keyValuePair">
<key>key2</key>
<value>val2</value>
</data>
</dataList>
<id>123</id>
</customer>
我使用以下POJO:
@XmlRootElement(namespace = "http://example.com")
public class Customer {
private String id;
private List<KeyValueData> data;
public Customer(){}
@XmlElement
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement
@XmlElementWrapper(name="dataList")
public List<KeyValueData> getData() {
return data;
}
public void setData(List<KeyValueData> data) {
this.data = data;
}
}
public class KeyValueData {
private String type;
private String key;
private String value;
public KeyValueData(){}
@XmlElement
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@XmlElement
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@XmlAttribute(namespace = "http://www.w3.org/2001/XMLSchema-instance" )
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
我用於un / marshalling的代碼:
InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
JAXBContext context = JAXBContext.newInstance(Customer.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
Customer customer = (Customer) unmarshaller.unmarshal(inputStream);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(customer, System.out);
這不是真的有效,我甚至無法解組初始的xml。 但是,如果我嘗試只編組一個POJO,我只需在代碼中設置字段。 我得到以下結果:
<ns3:customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns3="http://example.com">
<dataList>
<data xsi:type="keyValuePair">
<key>key1</key>
<value>val1</value>
</data>
<data xsi:type="keyValuePair">
<key>key2</key>
<value>val2</value>
</data>
</dataList>
<id>123</id>
</ns3:customer>
我如何擺脫這個ns3前綴?
我通過在包中添加命名空間定義來找到解決方案
package-info.java
@XmlSchema(namespace = "http://example.com", elementFormDefault = XmlNsForm.QUALIFIED)
package com.example;
(並從@XMLRootElement中刪除它)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.