Understanding JAXB @XmlRootElement annotation

前端 未结 2 676
悲&欢浪女
悲&欢浪女 2021-02-01 23:22

I am using the tutorial here for understanding JAXB.

When the writer comes to create the root of the document, the writer begins as below:

//This sta         


        
相关标签:
2条回答
  • 2021-02-02 00:09
    • @XmlRootElement annotation can be used to map a class or enum type to XML type.

    • When a top level class or an enum type is annotated with the @XmlRootElement annotation, then its value is represented as XML element in an XML document.

    • Follow the example given below to get more idea:

    Associate an element with XML Schema type

    // Example: Code fragment
     @XmlRootElement
     class Point {
        int x;
        int y;
        Point(int _x,int _y) {x=_x;y=_y;}
     }
    
     //Example: Code fragment corresponding to XML output
     marshal( new Point(3,5), System.out);
    
    
     <!-- Example: XML output -->
     <point>
       <x> 3 </x>
       <y> 5 </y>
     </point>
    
    0 讨论(0)
  • 2021-02-02 00:19

    I recommend using the package level @XmlSchema annotation to specify the namespace qualification for you model. A package level annotation goes in a special class called package-info that contains the exact content as shown below. That annotation will mean that all elements in your document without an explicit namespace given will use that namespace.

    org/example/foo/package-info.java

    @XmlSchema(
        namespace = "http://www.example.org/foo",
        elementFormDefault = XmlNsForm.QUALIFIED)
    package org.example.foo;
    
    import javax.xml.bind.annotation.XmlNsForm;
    import javax.xml.bind.annotation.XmlSchema;
    

    Overriding the Namespace

    • You can override the namespace given in the @XmlSchema for all properties in a class using the @XmlType annotation.
    • You can override the namespace for a given element using the namespace property on the @XmlRootElement or @XmlElement annotation.

    For More Information

    • http://blog.bdoughan.com/2010/08/jaxb-namespaces.html
    • http://blog.bdoughan.com/2012/07/jaxb-and-root-elements.html
    0 讨论(0)
提交回复
热议问题