[英]Creating an XML element with xsi:nil and attributes in .Net/Jaxb
I have an XML Schema that says: 我有一个XML模式说:
<xs:element name="employerOrganization" nillable="true" minOccurs="1" maxOccurs="1">
<xs:complexType>
<xs:sequence>
...
</xs:sequence>
<xs:attribute name="classCode" type="EntityClassOrganization" use="required"/>
<xs:attribute name="determinerCode" type="EntityDeterminerSpecific" use="required"/>
</xs:complexType>
</xs:element>
That means I must be able to create an instance that looks like this: 这意味着我必须能够创建一个如下所示的实例:
<employerOrganization classCode="ORG" determinerCode="INSTANCE" xsi:nil="true"/>
According to the XML Schema spec I can ( http://www.w3.org/TR/xmlschema-0/#Nils ). 根据XML Schema规范,我可以 ( http://www.w3.org/TR/xmlschema-0/#Nils )。 According to Microsoft .Net I cannot ( http://msdn.microsoft.com/en-us/library/ybce7f69(v=vs.100).aspx ) and as far as others tell me Jaxb cannot either.
根据Microsoft .Net,我无法 ( http://msdn.microsoft.com/zh-cn/library/ybce7f69(v=vs.100).aspx ),据其他人告诉我,Jaxb也不能。
Are both .Net and Jaxb uncompliant? .Net和Jaxb都不兼容吗? Can I override somehow to get the desired output?
我可以以某种方式覆盖以获得所需的输出吗?
In JAXB you can leverage a JAXBElement
for this. 在JAXB中,您可以利用
JAXBElement
。 The JAXBElement
can hold a value which has fields/properties mapped to XML attributes and a flag that tracks whether the element was nil. JAXBElement
可以保存一个值,该值具有映射到XML属性的字段/属性和一个跟踪元素是否为nil的标志。
Foo oo
Instead of having a field/property of type Bar
you specify JAXBElement<Bar>
. 您可以指定
JAXBElement<Bar>
而不是使用Bar
类型的字段/属性。
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {
@XmlElementRef(name="bar")
private JAXBElement<Bar> bar;
}
Bar 酒吧
Bar has fields/properties mapped to XML attributes. 栏具有映射到XML属性的字段/属性。
import javax.xml.bind.annotation.XmlAttribute;
public class Bar {
@XmlAttribute
private String baz;
}
ObjectFactory 对象工厂
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;
@XmlRegistry
public class ObjectFactory {
@XmlElementDecl(name="bar")
public JAXBElement<Bar> createBar(Bar bar) {
return new JAXBElement<Bar>(new QName("bar"), Bar.class, bar);
}
}
Demo 演示版
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class, ObjectFactory.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum19797412/input.xml");
Foo foo = (Foo) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(foo, System.out);
}
}
input.xml/Output input.xml /输出
<?xml version="1.0" encoding="UTF-8"?>
<foo>
<bar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" baz="Hello World" xsi:nil="true"/>
</foo>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.