Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML element with attribute and content using JAXB

Tags:

java

xml

jaxb

How can I generate the following XML using JAXB?

<sport type="" gender="">     sport description </sport> 
like image 252
James Avatar asked Apr 01 '11 14:04

James


People also ask

How do you add an attribute to an existing XML file in Java?

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.

What is the use of @XmlAccessorType XmlAccessType field?

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 .

How does JAXB read XML?

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.

How do you Unmarshal XML string to Java object using JAXB?

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.


1 Answers

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

  • http://bdoughan.blogspot.com/2011/06/jaxb-and-complex-types-with-simple.html
like image 66
bdoughan Avatar answered Oct 23 '22 14:10

bdoughan