4

I have an XML Schema that says:

<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). 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.

Are both .Net and Jaxb uncompliant? Can I override somehow to get the desired output?

4

1 回答 1

2

在 JAXB 中,您可以利用 aJAXBElement来实现这一点。可以保存一个值,该JAXBElement值具有映射到 XML 属性的字段/属性和一个跟踪元素是否为 nil 的标志。

Java 模型

Bar而不是您指定的类型的字段/属性JAXBElement<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 具有映射到 XML 属性的字段/属性。

import javax.xml.bind.annotation.XmlAttribute;

public class Bar {

    @XmlAttribute
    private String baz;

}

对象工厂

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

}

演示代码

演示

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

}

输入.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>
于 2013-11-05T21:01:45.287 回答