I am trying to convert an XML file to a Java Object, now, I have read of JAXB, XStream, Sax and DOM, I’d like to convert this sort of type of xml:
<testxml testtype="converting" duration="100.00" status="successful" />
it might be as well as:
<testxml testype="converting" duration="100.00"> successful </textxml>
I wanted to know if there is anything out there (and possibly not 3rd party) that I can use, without declaring a template in DTD or in JAXB in XSD but Java (therefore I will declare a java class called testxml with all the relevant variable i.e. testtype, duration, status>
Thank you all for your time.
Advertisement
Answer
The class below using JAXB Annotations will do exactly what you need, no need to create an XSD or a template using Java 1.6+:
@XmlRootElement public class TestXML { private String testtype; private double duration; private String status; public void setTesttype(String testtype) { this.testtype = testtype; } @XmlAttribute public String getTesttype() { return testtype; } public void setDuration(double duration) { this.duration = duration; } @XmlAttribute public double getDuration() { return duration; } public void setStatus(String status) { this.status = status; } @XmlValue public String getStatus() { return status; } public static void main(String args[]) { TestXML test = JAXB.unmarshal(new File("test.xml"), TestXML.class); System.out.println("testtype = " + test.getTesttype()); System.out.println("duration = " + test.getDuration()); System.out.println("status = " + test.getStatus()); } }
Using this as test.xml
:
<testxml testtype="converting" duration="100.00"> successful </testxml>