问题描述
使用JAXB,我想将空白列表编组为不存在的节点.我认为EclipseLink MOXy有这种可能性,但我无法使其正常工作.
Using JAXB I would like to have the possibility to marshal empty lists as absent nodes. I think that EclipseLink MOXy has that possibility, but I can't get it to work.
根据: http://wiki.eclipse.org/User :Rick.barkhouse.oracle.com/Test1 ,您应该可以这样做:
According to: http://wiki.eclipse.org/User:Rick.barkhouse.oracle.com/Test1 you should be able to do it like this:
@XmlElementWrapper(name="line-items", nillable=true)
@XmlNullPolicy(shouldMarshalEmptyCollections=false)
List<LineItem> item = null;
但是
shouldMarshalEmptyCollections
不是有效的属性.
我尝试使用eclipselink 2.4.0、2.4.1和2.5.0-M4.我在做什么错了?
I've tried using eclipselink 2.4.0, 2.4.1 and 2.5.0-M4. What am I doing wrong?
推荐答案
您可以使用 EclipseLink JAXB(MOXy) 的@XmlPath
映射来映射此用例.我将在下面的示例中演示如何与使用@XmlElementWrapper
进行比较.
You could use EclipseLink JAXB (MOXy)'s @XmlPath
mapping to map this use case. I'll demonstrate with an example below how it compares to using @XmlElementWrapper
.
根
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.properties
要将MOXy用作JAXB提供程序,您需要在与域模型相同的程序包中包含一个名为jaxb.properties
的文件,并带有以下条目(请参阅: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html ).
To use MOXy as your JAXB provider you need to include a file called jaxb.properties
in the same package as your domain model with the following entry (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示
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);
}
}
输出
在@XmlElementWrapper
用例中,为一个空集合写出一个元素,但在@XmlPath
用例中不是.
In the @XmlElementWrapper
use case an element is written out for an empty collection, but it is not for the @XmlPath
use case.
<?xml version="1.0" encoding="UTF-8"?>
<root>
<line-items-element-wrapper/>
</root>
这篇关于将空列表编组为JAXB的缺席节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!