如何使用 JAXB 将 null 值表示为空元素?

问题描述 投票:0回答:4

我的XSD结构如下:

<element name="XYZDate" maxOccurs="1" minOccurs="1" nillable="true" type="date"/>

当我在此字段中设置空值时,它允许我,但在从 JAXB 封送生成 XML 时,它会生成输出:

<XYZDate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>

而在结果中我希望输出为

<XYZDate/>
,即我不需要模式和其他属性。我在使用
XMLStreamWriter
的帮助下摆脱了这个问题,但它在一行中生成了完整的 XML。我需要格式良好的 XML。如果我需要使用
IndentingXMLStreamWriter
我的Java版本不支持它并且我无法控制Java容器来更改或修改。

请提出任何形成格式良好的 XML 的解决方案。

java xml jaxb
4个回答
16
投票

注意 #1: 我是 EclipseLink JAXB (MOXy) 领导者和 JAXB (JSR-222) 专家组成员。


注意 #2: 您看到的输出与您使用 JAXB 映射的输出相匹配。欲了解更多信息,请参阅:


将 NULL 表示为空元素

如果您想将 null 表示为空元素,有几个选项。

选项 #1 - 使用标准 JAXB API

日期适配器

您可以使用

XmlAdapter
来更改
Date
实例编组到 XML 的方式。我们将把日期转换为一个类的实例,该类具有一个用
@XmlValue
映射的属性(请参阅 http://blog.bdoughan.com/2011/06/jaxb-and-complex-types-with-simple.html )。 JAXB RI 不会为空值调用
XmlAdapter
机制,因此您需要使用 MOXy 等 JAXB impl。

package forum11743306;

import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.datatype.XMLGregorianCalendar;

public class DateAdapter extends XmlAdapter<DateAdapter.AdaptedDate, XMLGregorianCalendar>{

    @Override
    public AdaptedDate marshal(XMLGregorianCalendar date) throws Exception {
        AdaptedDate adaptedDate = new AdaptedDate();
        adaptedDate.value = date;
        return adaptedDate;
    }

    @Override
    public XMLGregorianCalendar unmarshal(AdaptedDate adaptedDate) throws Exception {
        return adaptedDate.value;
    }

    public static class AdaptedDate {
        @XmlValue
        public XMLGregorianCalendar value;
    }

}

使用

XmlAdapter
注释来引用
@XmlJavaTypeAdapter

package forum11743306;

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.datatype.XMLGregorianCalendar;

@XmlRootElement
public class Root {

    private XMLGregorianCalendar xyzDate;

    @XmlElement(name = "XYZDate", required=true, nillable = true)
    @XmlJavaTypeAdapter(DateAdapter.class)
    public XMLGregorianCalendar getXyzDate() {
        return xyzDate;
    }

    public void setXyzDate(XMLGregorianCalendar xyzDate) {
        this.xyzDate = xyzDate;
    }

}

选项 #2 - 使用 MOXy 的 @XmlNullPolicy 扩展

MOXy 提供了

@XmlNullPolicy
扩展,让您可以灵活地表示 null。

package forum11743306;

import javax.xml.bind.annotation.*;
import javax.xml.datatype.XMLGregorianCalendar;

import org.eclipse.persistence.oxm.annotations.*;

@XmlRootElement
public class Root {

    private XMLGregorianCalendar xyzDate;

    @XmlElement(name = "XYZDate", required=true, nillable = true)
    @XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
    public XMLGregorianCalendar getXyzDate() {
        return xyzDate;
    }

    public void setXyzDate(XMLGregorianCalendar xyzDate) {
        this.xyzDate = xyzDate;
    }

}

其他文件

以下文件可与任一选项一起使用来完成示例。

jaxb.properties

要将 MOXy 指定为您的 JAXB 提供程序,您需要在与域模型相同的包中包含一个名为

jaxb.properties
的文件,其中包含以下条目(请参阅:http://blog.bdoughan.com/2011/05/specifying- eclipselink-moxy-as-your.html)。

javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory

演示

package forum11743306;

import javax.xml.bind.*;
import javax.xml.datatype.DatatypeFactory;

import org.eclipse.persistence.Version;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);
        System.out.println(Version.getVersion());
        System.out.println(jc.getClass());

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Root root = new Root();
        root.setXyzDate(null);
        marshaller.marshal(root, System.out);

        root.setXyzDate(DatatypeFactory.newInstance().newXMLGregorianCalendar("2012-08-01"));
        marshaller.marshal(root, System.out);
    }

}

输出

2.4.0
class org.eclipse.persistence.jaxb.JAXBContext
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <XYZDate/>
</root>
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <XYZDate>2012-08-01</XYZDate>
</root>

4
投票

您应该阅读 nillable 和 minOccurs XSD 元素属性,因为

nil
empty
元素之间的差异在
XML
中非常显着。即
xsi:nil=true
SQL NULL
类似,但具有空元素表示空元素的存在。 :)
我知道这很令人困惑。

要解决您的特定问题,如果您使用

JAXB
序列化来生成该问题,我建议阅读 如何使用 JAXB 实例化空元素。问题本身向您展示了如何生成空元素。


2
投票

布莱斯的答案很好,但已经过时了。有一种更好、更简单的方法可以达到同样的效果。我搜索了很多论坛并结合了不同的解决方案来解决这个问题。我在这里分享是为了对其他人有帮助。


注意: 下面的解决方案比日期更通用。


方法 - 1:如果你想用 xml 中的空字符串替换所有 null 值

会话事件适配器类

将以下类添加到代码中方便的包中。

package com.dev

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

}

实体类

package com.dev;

import javax.xml.bind.annotation.*;

import org.eclipse.persistence.oxm.annotations.*;

@XmlRootElement(name = "Entity")
public class Entity {

    @XmlElement(name = "First_Name", required=true, nillable = true)
    private String firstName;

    @XmlElement(name = "Last_Name" , required=true, nillable = true)
    private String lastName;

    public Entity(){}

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

演示应用类

package com.dev;

import javax.xml.bind.*;
import org.eclipse.persistence.*;
import java.util.Map;
import java.util.HashMap;

public class DemoApp {

public static void main(String[] args) throws Exception {
    Map<String, Object> properties = new HashMap<String,Object>(1);
    SessionEventListener sessionEventListener = new NullSessionEventListener();
    properties.put(JAXBContextProperties.SESSION_EVENT_LISTENER, sessionEventListener);
    JAXBContext context = JAXBContextFactory.createContext(new Class[] {ListofEntities.class, list.get(0).getClass()},properties);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Entity entity = new Entity();
    entity.setfirstName(null);
    entity.setLastName(null);
    marshaller.marshal(entity, System.out);

    entity.setfirstName("Ramu");
    entity.setLastName("K");
    marshaller.marshal(entity, System.out);
}

}

输出:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <First_Name/>
   <Last_Name/>
</root>
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <First_Name>Ramu</First_Name>    
   <Last_Name>Ramu</Last_Name>   
</root>

方法 - 2:如果您只想用 xml 中的空字符串替换选定的 null 值

实体类

package com.dev;

import javax.xml.bind.annotation.*;

import org.eclipse.persistence.oxm.annotations.*;

@XmlRootElement(name = "Entity")
public class Entity {

    @XmlElement(name = "First_Name", required=true, nillable = true)
    @XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
    private String firstName;

    @XmlElement(name = "Last_Name" , required=true, nillable = true)
    private String lastName;

    public Entity(){}

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

演示应用类

package com.dev;

import javax.xml.bind.*;
import org.eclipse.persistence.*;

public class DemoApp {

public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContextFactory.createContext(new Class[] {ListofEntities.class, list.get(0).getClass()},null);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Entity entity = new Entity();
    entity.setfirstName(null);
    entity.setLastName(null);
    marshaller.marshal(entity, System.out);

    entity.setfirstName("Ramu");
    entity.setLastName("K");
    marshaller.marshal(entity, System.out);
}

}

输出:

在此输出中,我们看到当值为 null 时,仅显示带有 XmlNullPolicy 注释的元素。由于 jaxb 的默认行为,另一个元素被省略。

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <First_Name/>
</root>
<?xml version="1.0" encoding="UTF-8"?>
<root>
   <First_Name>Ramu</First_Name>    
   <Last_Name>Ramu</Last_Name>   
</root>

参考资料:

  1. 在哪里包含 jaxb.properties 文件?

  2. 将 null 值表示为 xml jaxb 中的空元素


0
投票

我投票赞成gbvb的答案。

我不明白你为什么想要这个,但是。

带有

xmlns:xsi
xsi:nil
的空元素是正确的方法。

如果没有这些属性,任何

reasonable
解析器都会给你空字符串
even if the element is self-closed

假设你想给客户一个整数值,这意味着许多玩家分数中的最高分数。

当您可以计算时,您可以给出正确的值。 当还没有玩家实际得分时,您应该将正确的值设置为

NULL
nil
,这意味着没有累积记录。

<highestScore among="128">98</highestScore>

可以说最高分是128次尝试中的98分。

还有

<highestScore among="0"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:nil="true"/>

可以说没有最高分,因为没有记录分数。

但是

<highestScore/>

除了一个简单的自闭合空元素之外没有任何意义。

© www.soinside.com 2019 - 2024. All rights reserved.