Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

xml - @XMLRootElement versus @XmlType

What's the difference between annotating a class with @XMLRootElement and @XMLType. I've been annotating classes with @XMLType when the structure will be used more than once within an XML schema and with @XMLRootElement when it will be used only once - is this the best approach?

A different but related question which I'll include here. The @XMLType annotation has an propOrder attribute to specify in which order its elements appear - is there an equivalent for @XMLRootElement?

I'm using these annotations in conjunction with JAX-WS annotations to create web services if that makes any difference.

question from:https://stackoverflow.com/questions/11520724/xmlrootelement-versus-xmltype

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The difference between XmlRootElement and XmlType is a matter of scoping. Remember this annotation is merely dictating the creation of the schema used to generate your XML. The XmlRootElement denotes a global element (with an anonymous or schema type):

<xs:element name=foo type="bar"> </xs:element> <-- schema type

while the XmlType is used to denote a local element (with an anonymous or complex type):

<xs:complexType name=bar> </xs:complexType> <-- complex type

The main differences in local/global here are in the hierarchy of the schema your object will appear in and whether you are declaring a schema type or complex type. The documentation for both of these annotations is well written and includes examples:

XmlRootElement

XmlType

EDIT: Addressing the propOrder question: you can use it on a global element if you are also declaring a local type:

@XmlRootElement (name="PersonElement")
@XmlType (propOrder={"firstname", "lastname"})
public class People{
    @XmlElement
    public String firstname;
    public String lastname;
}

This will yield something like:

<xs:element name="PersonElement" type="People"/>
<xs:complexType name="People">
    <xs:sequence>
        <xs:element name="firstname" type="xs:string"/>
        <xs:element name="lastname" type="xs:string"/>
    </xs:sequence>
</xs:complexType>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...