I have the following xml string. I want to convert it in to a java object, to map each tag with the fields of that object. Its better that if I can introduce different field names compared to tag name. How I can do that? I am looking on JAXB but I am still confused about parts like "ns4:response" and tags within tags. Thank you in advance...
<ns4:response>
<count>1</count>
<limit>1</limit>
<offset>1</offset>
<ns3:payload xsi:type="productsPayload">
<products>
<product>
<avgRating xsi:nil="true"/>
<brand>Candie's</brand>
<description>
<longDescription>
long descriptions
</longDescription>
<shortDescription>
short description
</shortDescription>
</description>
<images>
<image>
<altText>alternate text</altText>
<height>180.0</height>
<url>
url
</url>
<width>180.0</width>
</image>
</images>
<price>
<clearancePrice xsi:nil="true"/>
<regularPrice xsi:nil="true"/>
<salePrice>28.0</salePrice>
</price>
</product>
</products>
</ns3:payload>
</ns4:response>
Java Code to Convert an XML Document to String For converting the XML Document to String, we will use TransformerFactory , Transformer and DOMSource classes. "</BookStore>"; //Call method to convert XML string content to XML Document object.
JAXB definitionsUnmarshalling is the process of reading XML documents into Java objects. The JAXBContext class provides the client's entry point to the JAXB API. It provides API for marshalling, unmarshalling and validating.
The JAXBContext class provides the client's entry point to the JAXB API. It provides an abstraction for managing the XML/Java binding information necessary to implement the JAXB binding framework operations: unmarshal, marshal and validate.
JAXB is the Java standard (JSR-222) for converting objects to/from XML. The following should help:
Unmarshalling from a String
You will need to wrap the String
in an instance of StringReader
before your JAXB impl can unmarshal it.
StringReader sr = new StringReader(xmlString);
JAXBContext jaxbContext = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Response response = (Response) unmarshaller.unmarshal(sr);
Different Field and XML Names
You can use the @XmlElement
annotation to specify what you want the name of the element to be. By default JAXB looks at properties. If you wish to base the mappings on the fields then you need to set @XmlAccessorType(XmlAccessType.FIELD)
.
@XmlElement(name="count")
private int size;
Namespaces
The @XmlRootElement
and @XmlElement
annotations also allow you to specify namespace qualification where needed.
@XmlRootElement(namespace="http://www.example.com")
public class Response {
}
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