将空值表示为 xml jaxb 中的空元素 [英] Represent null value as empty element in xml jaxb

查看:47
本文介绍了将空值表示为 xml jaxb 中的空元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 jaxb 中将空值显示为空元素.我正在使用 jaxb 的 moxy 实现.我找到了这个选项

I need to display null value as empty element in jaxb. I am using moxy implementation of jaxb. I found this option

@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)

是否有任何类似的扩展可以应用于类级别(对于其中定义的所有元素)

Is there any similar extension that can be applied at Class level (for all elements defined in it)

推荐答案

我强烈建议用没有节点或用 xsi:nil="true" 表示 null 属性.这对模式验证最有效(即 不是 xsd 类型的有效元素:int.但是如果你不能,这里是你如何完成你的用例:

I would strongly recommend representing null with either the absence of the node or with the xsi:nil="true" attribute. This works best with schema validation (i.e. <age/> or <age></age> is not a valid element of type xsd:int. However if you can't here is how you can accomplish your use case:

标准 JAXB 行为

使用标准 API,您可以控制是否将 null 表示为不存在的节点,或者使用带有 @XmlElement 注释的 xsi:nil="true"(请参阅:http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html).

Using the standard APIs you can control whether null is represented as an absent node or with xsi:nil="true" with the @XmlElement annotation (see: http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html).

import javax.xml.bind.annotation.*;

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

    private String street;

    @XmlElement(nillable=true)
    private String city;

}

以下是两个字段的值都为空时的 XML 输出.

Below is the XML output if the values of both fields are null.

<?xml version="1.0" encoding="UTF-8"?>
<address>
   <city xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</address>

<小时>

MOXy - 覆盖每个班级的这种行为

MOXy 没有提供注释来为类上的所有属性指定空策略.但是,您可以通过 @XmlCustomizer 注释利用 DescriptorCustomizer 并调整本机 MOXy 映射元数据来完成相同的事情.

MOXy does not provide an annotation to specify the null policy for all the properties on a class. However you can leverage a DescriptorCustomizer via the @XmlCustomizer annotation and tweak the native MOXy mapping metadata to accomplish the same thing.

DescriptorCustomizer (AddressCustomizer)

import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.oxm.mappings.XMLDirectMapping;
import org.eclipse.persistence.oxm.mappings.nullpolicy.XMLNullRepresentationType;

public class AddressCustomizer implements DescriptorCustomizer {

    @Override
    public void customize(ClassDescriptor descriptor) throws Exception {
        for(DatabaseMapping mapping : descriptor.getMappings()) {
            if(mapping.isAbstractDirectMapping()) {
                XMLDirectMapping xmlDirectMapping = (XMLDirectMapping) mapping;
                xmlDirectMapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.EMPTY_NODE);
                xmlDirectMapping.getNullPolicy().setNullRepresentedByEmptyNode(true);
            }
        }
    }

}

DomainModel(地址)

import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlCustomizer;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlCustomizer(AddressCustomizer.class)
public class Address {

    private String street;

    @XmlElement(nillable=true)
    private String city;

}

输出

<?xml version="1.0" encoding="UTF-8"?>
<address>
   <street/>
   <city/>
</address>

<小时>

MOXy - 覆盖所有班级的这种行为

如果您想覆盖所有映射类的空处理,我建议改用 SessionEventListener.如果您愿意,也可以使用这种方法更新单个类的元数据.

If instead you want to override null handling for all of the mapped classes I would recommend using a SessionEventListener instead. If you prefer you could also use this approach to update the metadata for a single class.

SessionEventListener (NullPolicySessionEventListener)

import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.oxm.mappings.XMLDirectMapping;
import org.eclipse.persistence.oxm.mappings.nullpolicy.XMLNullRepresentationType;
import org.eclipse.persistence.sessions.*;

public class NullPolicySessionEventListener extends SessionEventAdapter {

    @Override
    public void preLogin(SessionEvent event) {
        Project project = event.getSession().getProject();
        for(ClassDescriptor descriptor : project.getOrderedDescriptors()) {
            for(DatabaseMapping mapping : descriptor.getMappings()) {
                if(mapping.isAbstractDirectMapping()) {
                    XMLDirectMapping xmlDirectMapping = (XMLDirectMapping) mapping;
                    xmlDirectMapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.EMPTY_NODE);
                    xmlDirectMapping.getNullPolicy().setNullRepresentedByEmptyNode(true);
                }
            }
        }
     }

}

演示代码

import java.util.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.sessions.SessionEventListener;

public class Demo {

    public static void main(String[] args) throws Exception {
        Map<String, Object> properties = new HashMap<String, Object>(1);
        SessionEventListener sessionEventListener = new NullPolicySessionEventListener();
        properties.put(JAXBContextProperties.SESSION_EVENT_LISTENER, sessionEventListener);
        JAXBContext jc = JAXBContext.newInstance(new Class[] {Address.class}, properties);

        Address address = new Address();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(address, System.out);
    }

}

输出

<?xml version="1.0" encoding="UTF-8"?>
<address>
   <street/>
   <city/>
</address>

这篇关于将空值表示为 xml jaxb 中的空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆