A class that describes an XML element, a top-level element, i.e., one of the can function as an XML document, s Hould is annotated with XmlRootElement
. Its optional elements is name
and namespace
. By default, the class name is used as the name.
This annotation corresponds to a xsd:element
construct being used at the outermost level of a XML schema. The sequence of Java, XML and schema snippets given below illustrates this relation.
@XmlRootElement (name= "Doc" )publicclass Document { @XmlElement protected foo foo; // ...}
<? XML version= "1.0" encoding= "UTF-8" ?> < Doc > < Foo >... </ Foo > </ Doc >
<?XML version= "1.0" encoding= "UTF-8"?><Xsd:complextypename= "Foo"> ...</Xsd:complextype><Xsd:complextypename= "Document"> <xsd:sequence> <xsd:elementname= "Foo"type= "Foo"/> </xsd:sequence></Xsd:complextype><xsd:elementname= "Doc"type= "Document"/>
It's a surprising fact so if all of the your Java classes permit a straightforward mapping to XML Schema, could be the XmlRootElement
O nly annotation You has to make! Here's a small set of classes, that's even capable of marshalling a Map<K,V>
.
ImportJava.util.HashMap;ImportJava.util.Map;Importjavax.xml.bind.annotation.*; @XmlRootElement (name= "Doc") Public classDocType { PublicMap<keytype,entrytype> Key2entry =NewHashmap<keytype,entrytype>(); PublicDocType () {}}ImportJavax.xml.datatype.*; Public classKeyType { PublicString event; PublicXmlgregoriancalendar datetime; PublicKeyType () {} PublicKeyType (String event, Xmlgregoriancalendar datetime) { This. event =event; This. DateTime =datetime; }} Public classEntryType { PublicString Program; PublicString Artists; Publicentrytype () {} Publicentrytype (String artists, string program) { This. Artists =artists; This. program =Program ; }}
Applying the usual incantations for creating and marshalling content, your could produce XML data like so:
<Doc> <Key2entry> <entry> <Key> <Event>Soiree</Event> <datetime>2008-08-23t20:00:00</datetime> </Key> <value> < Program>Mans on the Moon</ Program> <Artists>R.e.m</Artists> </value> </entry> </Key2entry></Doc>
XMLGregorianCalendar
xsd:dateTime
The is mapped to, and the ' between the date and the time T
are just right, according to the Schema Datatyp ES specification. You can see this JAXB had to "invent" a few tag names for the intermediary element levels separating map entries from each Other, and key data from the value data, but you ' d has to does something similar if you ' d design it yourself.
Jaxb-annotations, top-level elements:xmlrootelement