my dog learned polymorphism
The moose likes XML and Related Technologies and the fly likes xml parsing from a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "xml parsing from a string" Watch "xml parsing from a string" New topic

xml parsing from a string

Jason Mill

Joined: Jul 29, 2003
Posts: 6
I'm new to java but making good progress, though still having trouble knowing which api to use for what. I'm trying to extract xml data from a string, the string being the contents of an xml file.
I'm trying to use a SAXParser (xerces) but the xmlString below is expecting the url where the xml file is.
SAXParser xr = new SAXParser();
xr.setContentHandler( new XmlParser() );
Unfortunatly I can't access the url directly from this code. What can I use to parse a string of xml data?
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
Moving to the XML forum.

"JavaRanch, where the deer and the Certified play" - David O'Meara
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Look at the parse() signatures available on SAXParser. A couple of them take InputStream parameters. Can we turn your String into an InputStream? InputStream docs show a number of subclasses. ByteArrayInputStream can be constructed with a byte[] and we can turn String into byte[]. So I'd give it a try with:
parse( new ByteArrayInputStream( myString.getBytes() ) );
Hope that helps. (Hope it works!)

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Lasse Koskela

Joined: Jan 23, 2002
Posts: 11962
SAXParser.parse(...) also accepts an InputSource:

Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
I agree. Here's the link:
subject: xml parsing from a string
It's not a secret anymore!