Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting XML to Java objects [closed]

Tags:

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...

like image 282
DD. Avatar asked Jul 18 '10 15:07

DD.


People also ask

How do you Unmarshal XML string to Java object using JAXB?

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.


1 Answers

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.

like image 97
nos Avatar answered Sep 16 '22 21:09

nos