【问题标题】:JAXB unmarshaling with namespaces, but without prefixJAXB 使用名称空间解组,但没有前缀
【发布时间】:2019-10-29 21:45:36
【问题描述】:

我想用JAXB来

  1. 将 xml 解组为 java 对象,
  2. 将其编组回 xml
  3. 并使用命名空间产生完全相同的输出

这是原始的 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;
  }

}

我用于取消/编组的代码:

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 前缀?

【问题讨论】:

    标签: java xml namespaces jaxb


    【解决方案1】:

    我通过在包级别中添加命名空间定义找到了解决方案

    包信息.java

    @XmlSchema(namespace = "http://example.com", elementFormDefault = XmlNsForm.QUALIFIED)
    package com.example;
    

    (并将其从@XMLRootElement 中删除)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多