简体   繁体   中英

Convert Java object to XML without any @XmlRootElement in the Java class

I just want to convert a simple Java object to XML and in the Java object none of the elements are mentioned as @XmlRootElement and @XmlAttribute . Is this possible to do with JAXB ?

My Java object looks like below:

public class myrequest implements java.io.Serializable {
    private java.lang.String id;

    private java.lang.String code;

    private java.lang.String type;

    private java.lang.String name;

    private java.lang.String count;
and getters and setters....

You can marshal your Java object without need for JAXB annotations by using the marshal methods from class javax.xml.bind.JAXB .

Quoted from its javadoc:

Class that defines convenience methods for common, simple use of JAXB.
Methods defined in this class are convenience methods that combine several basic operations in the JAXBContext, Unmarshaller, and Marshaller. They are designed to be the prefered methods for developers new to JAXB.

You can use it for example like this:

myrequest obj = new myrequest();
obj.setId("1");
obj.setCode("2");
obj.setCount("3");
JAXB.marshal(obj, System.out);

And you will get the following XML output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myrequest>
    <code>2</code>
    <count>3</count>
    <id>1</id>
</myrequest>

Yes; if you want to do this, then you need to create a JAXBElement<myrequest> and pass that to the marshaller, instead of directly passing a myrequest to the marshaller. Example:

myrequest request = ...;

JAXBContext context = new JAXBContext(myrequest.class);
Marshaller marshaller = context.createMarshaller();

// Create a JAXBElement wrapper
JAXBElement<myrequest> element = new JAXBElement<>(request);

// Pass that to the marshaller
marshaller.marshall(element, System.out);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM