aspose file tools*
The moose likes Java in General and the fly likes Reading in XML into Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Reading in XML into Objects" Watch "Reading in XML into Objects" New topic
Author

Reading in XML into Objects

Ryan Waggoner
Ranch Hand

Joined: Jun 27, 2007
Posts: 75
Hi guys,
I am working on a little XML piece and well...

I have this little XML reader method



And this is the XML file I am reading in



I want to create an instance of a House, but so far the only way I can do it is, putting a lot of little if statements like:

If (isStartElement && element.name.equals("ownerName")
set ownerName = element.getCharacter

Any suggestions?

Thanks!
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2419
    
    7

I think there is easier way using JAXP (Java API for XML Processing). If you are already using it good.

To make you if statements go away? Why not have a House class? Can't say much without knowing architecture.


K. Tsang JavaRanch SCJP5 SCJD/OCM-JD OCPJP7 OCPWCD5
Ryan Waggoner
Ranch Hand

Joined: Jun 27, 2007
Posts: 75
Hey sorry,
I do have a house class, and it has all the properties you see in the xml document. I am having troublelinking the document to my house class.
Hong Anderson
Ranch Hand

Joined: Jul 05, 2005
Posts: 1936
Have you tried Xstream?


SCJA 1.0, SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCJP 5.0, SCEA 5, SCBCD 5; OCUP - Fundamental, Intermediate and Advanced; IBM Certified Solution Designer - OOAD, vUML 2; SpringSource Certified Spring Professional
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38873
    
  23
Too difficult a question for us beginners, Moving.
phil mitchel
Greenhorn

Joined: Sep 10, 2008
Posts: 4
look into JAXB / JAX-WS, unmarshal your XML directly into the objects generated from xjc. you could wirte adaptors to wrap the generated classes to fit your needs or have constructors in your own classes that take the generated objects as args.

if don't already have a proper XSD, you can create the XSD on this site:
http://www.hitsw.com/xml_utilites/

run xjc from the command line, pass the XSD as an argument - or google how to add it as an extrnal tool in eclipse

here's some bare bones code I dug out to show how to marshal / unmarshal



rgds,
Phil
Ryan Waggoner
Ranch Hand

Joined: Jun 27, 2007
Posts: 75
Working wonderfully

Thanks a lot!
 
jQuery in Action, 2nd edition
 
subject: Reading in XML into Objects