What's the best way to convert XML into Java objects?
I don't want a like for like representation, but would like to pull out certain data from the XML and populate a Java object. I had a look at XStream, but didn't really like the whole "move down, move up" type of stuff. I would prefer a DOM like object when writing converters...
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.
If you have an XML schema , JAXB is nice - comes as part of the JDK. Generate java classes by running e.g. xjc -p foo myschema.xsd
To read an XML file and get back an object (from classes generated by the xjc tool):
JAXBContext context = JAXBContext.newInstance(FooObj.class); Unmarshaller unMarshaller = context.createUnmarshaller(); FooObj param = (FooObj) unMarshaller.unmarshal(new FileInputStream("Foo.xml"));
You can do similar things if you only want parts of an XML document converted to an object, you should e.g. be able to give JAXB part of a DOM document, instead of a whole file as done above.
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