有没有办法让JAXB在nillable xmlns:xsi
上正确打印xsi:nill
和@XmlRootElement
?
public class XmlValueTest {
public static void main(final String[] args) throws JAXBException {
final JAXBContext context =
JAXBContext.newInstance(Wrapper.class, Value.class);
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(Value.newInstance(null), System.out);
marshaller.marshal(Value.newInstance("null"), System.out);
marshaller.marshal(Wrapper.newInstance(null), System.out);
marshaller.marshal(Wrapper.newInstance("null"), System.out);
}
}
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement
class Value {
public static Value newInstance(final String raw) {
final Value instance = new Value();
instance.raw = raw;
return instance;
}
@XmlValue
private String raw;
}
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement
class Wrapper {
public static Wrapper newInstance(final String raw) {
final Wrapper wrapper = new Wrapper();
wrapper.raw = raw;
return wrapper;
}
@XmlElement(nillable = true, required = true)
private String raw;
}
打印
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<value/> <!-- is this normal? -->
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<value>null</value>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wrapper>
<raw xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</wrapper>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wrapper>
<raw>null</raw>
</wrapper>
我只是想知道有没有办法让第一个<value/>
配备xmlns:xsi
和xsi:nill
。
答案 0 :(得分:1)
注意:我是EclipseLink JAXB (MOXy)潜在客户,也是JAXB (JSR-222)专家组的成员。
我不相信有一种方法可以使用标准的JAXB API来实现这一点。以下示例可以通过@XmlElement(nillable=true)
与@XmlPath("text()")
一起使用来获得所需的行为。
<强>值强>
package forum11796699;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement
public class Value {
private String value;
@XmlElement(nillable=true)
@XmlPath("text()")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
<强> 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 forum11796699;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Value.class);
Value value = new Value();
value.setValue(null);
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(value, System.out);
}
}
<强>输出强>
<?xml version="1.0" encoding="UTF-8"?>
<value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>