It's not a secret anymore!
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

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 &&"ownerName")
set ownerName = element.getCharacter

Any suggestions?

K. Tsang

Joined: Sep 13, 2007
Posts: 3042

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 OCPJP7 OCPWCD5 OCPBCD5 OCPWSD5 OCMJEA5 part 1 part 2/3
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

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

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:

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

Ryan Waggoner
Ranch Hand

Joined: Jun 27, 2007
Posts: 75
Working wonderfully

Thanks a lot!
I agree. Here's the link:
subject: Reading in XML into Objects
It's not a secret anymore!