File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes XML and Related Technologies and the fly likes How to read XML data Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "How to read XML data" Watch "How to read XML data" New topic

How to read XML data

Amit Bathla
Ranch Hand

Joined: Feb 11, 2005
Posts: 51
I have XML data in one string, and I want to extract data from its tag, how to do that in J2SE.

eg. My Data:

String str = "<tag1>data1</tag1><tag2>data2</tag2>"

how to read data1 and data2 from string.. ??

Note: I am using Google Health API to extract the profile and it is returning profile information in the form of XML.
Please suggest some way to read it....
Thanks and Regards

University of Florida
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42959
First of all, note that what you posted is not valid XML - it does not have one single root element. I hope that's not actually what Google Health uses.

Both the DOM and SAX APIs can read from an InputStream (which is easily constructed from a String). Check the java.xml.parsers.DocumentBuilder and SAXParser javadocs for the relevant methods. Basic examples of how to use both can be found here, particularly e510 and e517.
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 378
Ulf, you mean not well formed?

You could also try StAX. StAX is a core JSE API in 1.6 and comes with a bundled implementation.

this and this should help if you are interested.
I agree. Here's the link:
subject: How to read XML data
It's not a secret anymore!