jaxb - 输出空元素

标签 jaxb

我有一个带有两个字段“名称”和“地址”的对象。 JAXB 在将对象转换为 XML 时忽略空元素。

例如:如果我有 name="xyz"和 address=null 那么 out 将是

<name>xyz</name>

但我想要作为输出
<name>xyz</name>
<address></address>

我已经看到选项 @XmlElement(nillable="true")但这使输出为
<name>xyz</name>
<address xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

请帮助我获得所需的输出。

提前致谢。

最佳答案

JAXB (JSR-222)实现将输出一个空字符串 ""作为空元素的值。您可以设置 address属性来获得想要的效果。

更新 #1

I have updated my question. Basically the address element is NULL. Is this solution applicable to that as well?



您可以利用 Marshal Event Callbacks调整 address 的值.

import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {

    private String name;
    private String address;

    private void beforeMarshal(Marshaller marshaller) {
        if(null == address) {
            address = "";
        }
    }

    private void afterMarshal(Marshaller marshaller) {
        if("".equals(address)) {
            address = null;
        }
    }

}

更新 #2

The only concern is that if I have 10 fields in the class I will have to write if for all the fields. Is there any other solution?



如果您使用 EclipseLink MOXy作为您的 JAXB 提供商(我是 MOXy 负责人),那么您可以使用 XmlAdapter对于这个用例。

XmlAdapter (StringAdapter)

package forum14691333;

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class StringAdapter extends XmlAdapter<String, String> {

    @Override
    public String marshal(String string) throws Exception {
        if(null == string) {
            return "";
        }
        return string;
    }

    @Override
    public String unmarshal(String string) throws Exception {
        if("".equals(string)) {
            return null;
        }
        return string;
    }

}

包裹信息

然后,如果您在包级别指定它,它将适用于类型 String 的所有映射字段/属性。在那个包裹内。

@XmlJavaTypeAdapter(value=StringAdapter.class, type=String.class)
package forum14691333;

import javax.xml.bind.annotation.adapters.*;

更多信息
  • http://blog.bdoughan.com/2012/02/jaxb-and-package-level-xmladapters.html
  • http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
  • 关于jaxb - 输出空元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14691333/

    相关文章:

    java - 无法将类型编码为 XML 元素,因为缺少 @XmlRootElement 注释

    xml - 调用 Jersey api 时无法指定接受哪种响应类型

    java - 将 JAXB 与 JgraphX 一起使用?

    java - 解析具有多个属性的 XML 以列出

    Java JAXB XJC代码生成表单XSD模式问题

    java - JAXB - 包含 HTML 页面的解码元素

    jboss - Resteasy JAXB 上下文未获取我的 ObjectFactory

    java - 对象能否调用 JAXB 将其解码到自身(或 'this' )?

    java - 将java对象编码为不同格式的XML?

    java - 高效去除UTF字节序标记