使用 JAXB 将空列表编组为缺席节点

2024-02-02

使用 JAXB 我希望能够将空列表编组为缺失节点。我认为 EclipseLink MOXy 有这种可能性,但我无法让它工作。

根据:http://wiki.eclipse.org/User:Rick.barkhouse.oracle.com/Test1 http://wiki.eclipse.org/User:Rick.barkhouse.oracle.com/Test1你应该能够这样做:

@XmlElementWrapper(name="line-items", nillable=true)
@XmlNullPolicy(shouldMarshalEmptyCollections=false)
List<LineItem> item = null;

But

shouldMarshalEmptyCollections

不是有效的属性。

我尝试过使用 eclipselink 2.4.0、2.4.1 和 2.5.0-M4。我究竟做错了什么?


你可以使用EclipseLink JAXB (MOXy) http://www.eclipse.org/eclipselink/moxy.php's @XmlPath映射来映射此用例。我将通过下面的示例来演示它与使用的比较@XmlElementWrapper.

Root

package forum13268598;

import java.util.List;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;

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

    @XmlElementWrapper(name="line-items-element-wrapper")
    List<LineItem> item1 = null;

    @XmlPath("line-items-xml-path/item1")
    List<LineItem> item2 = null;

}

jaxb.属性

要使用 MOXy 作为 JAXB 提供程序,您需要包含一个名为jaxb.properties在与域模型相同的包中,包含以下条目(请参阅:http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).

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

Demo

package forum13268598;

import java.util.ArrayList;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Root root = new Root();
        root.item1 = new ArrayList<LineItem>();
        root.item2 = new ArrayList<LineItem>();

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

}

Output

In the @XmlElementWrapper用例为空集合写出一个元素,但它不适用于@XmlPath用例。

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <line-items-element-wrapper/>
</root>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 JAXB 将空列表编组为缺席节点 的相关文章

随机推荐