user3276342 user3276342 - 3 months ago 11
Java Question

parse xml string using jaxb

I am trying to parse an xml string using jaxb.
In fact , I need to extract the decimal value in literal .

That's the XML string :

<results>
<result>
<binding name="value">
<literal datatype="http://www.w3.org/2001/XMLSchema#decimal">369.0</literal>
</binding>
</result>
</results>


I have a java class Results :

package client;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Results {

@XmlElement
String result;

@XmlElement
Double binding;

@XmlElement
Double literal;
public Double getLiteral()
{
return literal;
}
public Double geBinding()
{
return binding;
}
public String getResult()
{
return result;
}

}


When I tried to print the value , I'm getting null .So How can I get the decimal value between literal tag ?

Results re=(Results) JAXBContext.newInstance(Results.class)
.createUnmarshaller()
.unmarshal(new StringReader(my_xml));

System.out.println(re.getLiteral());

Answer

Your Results class does not reflect the structure of the XML you're trying to parse. The results element consists of a result element, which in turn consists of binding and that consists of literal.

To do this through JAXB, we'll have to follow a similar structure.

@XmlRootElement
public class Results {

    @XmlElement
    Result result;

    public Result getResult() {
        return result;
    }
}

public class Result {
    @XmlElement
    Binding binding;

    public Binding getBinding() {
        return binding;
    }
}

public class Binding {
    @XmlElement
    Double literal;

    public Double getLiteral() {
        return literal;
    }
}

To access the value of literal, we can call the getters like results.getResult().getBinding().getLiteral().

However, if this is a one off occurance and your application would not be dealing with XML a lot, you can consider using XPath.

Comments