JAXB with nillable root

349 views Asked by At

I have a simple XSD that can not be modified (provided by a third-party). I am trying to use XJC to generate java classes for the XSD. The very simplified XSD is:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="receive" nillable=true />
</xs:schema> 

I want to marshal an object out to XML so the element is set to nil. When I generate java classes with XJC, I get an ObjectFactory that has a JAXBElement<Object> createReceive(Object) method. However, there is no @XmlElementRoot annotation. I saw this question and answer, however I also do not have access to third-party plugins. Is there a possible solution through bindings, or any other native solution?

1

There are 1 answers

0
TryThis On

Figured out this was far easier than I was making it, or than the linked question implied. I was hung up on the fact there was no @XmlElementRoot, but it turns out to be unnecessary.

simple.xsd:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="receive" nillable="true" />
</xs:schema>

On command line, ran .../jdk1.8/bin/xjc simple.xsd which generated ObjectFactory. The one method in ObjectFactory had the signature public JAXBElement<Object> createReceive(Object value).

Created the below implementation code:

package aTest;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import generated.ObjectFactory;

public class start {

  public static void main(final String[] args) {
    final ObjectFactory factory = new ObjectFactory();
    final JAXBElement<Object> element = factory.createReceive(null);

    try {
      final JAXBContext jaxbContext = JAXBContext.newInstance(JAXBElement.class);
      final Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

      jaxbMarshaller.marshal(element, System.out);
    } catch (final JAXBException e) {
      e.printStackTrace();
    }
  }
}

This generated the following output as desired:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<receive xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>