在 xml jaxb 中将空值表示为空元素

2022-09-04 01:47:42

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

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

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


答案 1

我强烈建议使用缺少节点或属性来表示。这最适合架构验证(即 或 不是 类型的有效元素。但是,如果您不能,请在此处完成用例:nullxsi:nil="true"<age/><age></age>xsd:int

标准 JAXB 行为

使用标准 API,您可以控制 null 是表示为缺少的节点,还是使用注释表示 null(请参阅:http://blog.bdoughan.com/2012/04/binding-to-json-xml-handling-null.html)。xsi:nil="true"@XmlElement

import javax.xml.bind.annotation.*;

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

    private String street;

    @XmlElement(nillable=true)
    private String city;

}

下面是 XML 输出(如果两个字段的值都为 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 不提供注释来为类上的所有属性指定 null 策略。但是,您可以利用 via 注释并调整本机 MOXy 映射元数据来完成相同的操作。DescriptorCustomizer@XmlCustomizer

描述符自定义器(地址自定义器)

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);
            }
        }
    }

}

域模型(地址)

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 - 覆盖所有类的此行为

相反,如果您想覆盖所有映射类的空值处理,我建议改用 a。如果您愿意,还可以使用此方法更新单个类的元数据。SessionEventListener

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>

答案 2

如果类中只有 String 字段,则一种“不好的做法”解决方法是重写元素的 setter,如下所示:

public class Address {

  private String street;

  @XmlElement(name = "street")
  public void setStreet(String street){
    this.street = street;
    if (this.street == null){
      this.street = ""; // Not NULL, empty string like new String()!
    }
  }
}

这不适用于其他类型,如日期或数字!但有时String就足够了。

@Blaise从长远来看,Doughan的答案似乎要好得多,如果你能处理它。:)


推荐