How can I generate the following XML using JAXB?
<sport type="" gender=""> sport description </sport>
Add a new attribute to the element, using setAttribute(String name, String value) . Call void prettyPrint(Document xml) method of the example. The method gets the xml Document and converts it into a formatted xml String, after transforming it with specific parameters, such as encoding.
1.2) @XmlAccessorTypeIt defines the fields or properties of your Java classes that the JAXB engine uses for including into generated XML. It has four possible values. FIELD – Every non static, non transient field in a JAXB-bound class will be automatically bound to XML, unless annotated by XmlTransient .
To read XML, first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations. Now get the Unmarshaller instance from JAXBContext . It's unmarshal() method unmarshal XML data from the specified XML and return the resulting content tree.
To unmarshal an xml string into a JAXB object, you will need to create an Unmarshaller from the JAXBContext, then call the unmarshal() method with a source/reader and the expected root object.
Annotate type and gender properties with @XmlAttribute
and the description property with @XmlValue
:
package org.example.sport; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement public class Sport { @XmlAttribute protected String type; @XmlAttribute protected String gender; @XmlValue; protected String description; }
For More Information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With