|
Re: Trying to Marshall/Unmarshall xjc generated classes that don't have a @XmlRootElement annotation [message #1060407 is a reply to message #1060223] |
Fri, 24 May 2013 13:55  |
|
Hi Eric,
I will demonstrate how you can handle this use case using the following XML Schema. The schema contains 2 named complex types: foo and bar. The foo type has 1 corresponding global element, and the bar type has 2.
XML Schema (schema.xsd)
<?xml version="1.0" encoding="UTF-8"?>
<schema
xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.example.org/schema"
xmlns:tns="http://www.example.org/schema"
elementFormDefault="qualified">
<element name="foo" type="tns:foo"/>
<complexType name="foo">
<attribute name="a"/>
</complexType>
<element name="bar1" type="tns:bar"/>
<element name="bar2" type="tns:bar"/>
<complexType name="bar">
<attribute name="b"/>
</complexType>
</schema>
Default Generation - xjc schema.xsd
If we generate a Java model from this XML schema we will get Foo and Bar classes and neither of them will be annotated with @XmlRootElement. Instead there will be @XmlElementDecl declarations for each of the global elements in the generated ObjectFactory class.
ObjectFactory objectFactory = new ObjectFactory();
Foo foo = new Foo();
JAXBElement<Foo> fooElement = objectFactory.createFoo(foo);
Bar bar = new Bar();
JAXBElement<Bar> bar1Element = objectFactory.createBar1(bar);
JAXBElement<Bar> bar2Element = objectFactory.createBar2(bar);
Customized Generation - xjc -extension -b binding.xml schema.xsd
We can leverage an XJC extension to create an @XmlRootElement for a class when there is only 1 global element. For the XML schema in this example an @XmlRootElement will be generated on the Foo class, but not on the Bar class. The binding.xml file looks like:
<?xml version="1.0"?>
<jxb:bindings
version="1.0"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc= "http://java.sun.com/xml/ns/jaxb/xjc"
jxb:extensionBindingPrefixes="xjc"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<jxb:bindings schemaLocation="schema.xsd" node="/xs:schema">
<jxb:globalBindings>
<xjc:simple/>
</jxb:globalBindings>
</jxb:bindings>
</jxb:bindings>
For More Information
- http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html
-Blaise
[Updated on: Fri, 24 May 2013 13:57] Report message to a moderator
|
|
|
Powered by
FUDForum. Page generated in 0.02354 seconds