Reputation: 19
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());
Upvotes: 0
Views: 587
Reputation: 45005
One way to simplify your code is to use MOXy
the EclipseLink's JAXB
and its XmlPath
annotation allowing to provide a XPATH
such that you can map directly element or attribute content to your field which allow to avoid having an additional class for each sub element.
For example in your case, the mapping would be:
@XmlPath("result/binding/literal/text()")
Double literal;
You will need to add this dependency to your project:
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.3</version>
</dependency>
And specify explicitly the context factory to use thanks to a system property to set in your launch command -Djavax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Here is a good article about MOXy
describing how to simplify your code with its features.
Upvotes: 0
Reputation: 375
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.
Upvotes: 1