简体   繁体   中英

Creating an XML element with xsi:nil and attributes in .Net/Jaxb

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?

In JAXB you can leverage a JAXBElement for this. The JAXBElement can hold a value which has fields/properties mapped to XML attributes and a flag that tracks whether the element was nil.

Java Model

Foo

Instead of having a field/property of type Bar you specify 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

Bar has fields/properties mapped to XML attributes.

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 Code

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

<?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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM