XmlRootElement

XmlRootElement标记根元素

package com.test;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class RootElement {
    @XmlElement
    String name;
    @XmlElement
    String address;

    public void setName(String name) {
        this.name = name;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public static void main(String[] args) throws Exception {
        RootElement root = new RootElement();
        root.setName("ROSS");
        root.setAddress("GZ");
        
        JAXBContext context = JAXBContext.newInstance(RootElement.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(root, System.out);
    }
    
}

输出



    ROSS
    
GZ

如果不加@XmlRootElement,会报错

Exception in thread "main" javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.istack.internal.SAXException2: 由于类型 "com.test.RootElement" 缺少 @XmlRootElement 注释, 无法将该类型编集为元素]
    at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(Unknown Source)
    at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source)
    at com.test.RootElement.main(RootElement.java:28)
Caused by: com.sun.istack.internal.SAXException2: 由于类型 "com.test.RootElement" 缺少 @XmlRootElement 注释, 无法将该类型编集为元素
    at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(Unknown Source)
    at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(Unknown Source)
    ... 4 more

根元素默认和类同名,可以更改

package com.test;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="MyRootElement")
public class RootElement {
    @XmlElement
    String name;
    @XmlElement
    String address;
    
    public void setName(String name) {
        this.name = name;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public static void main(String[] args) throws Exception {
        RootElement root = new RootElement();
        root.setName("ROSS");
        root.setAddress("GZ");
        
        JAXBContext context = JAXBContext.newInstance(RootElement.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.marshal(root, System.out);
    }
}

输出



    ROSS
    
GZ

你可能感兴趣的:(XmlRootElement)