Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Parsing a string using Java and SAX?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I'm trying to parse the xml from a string instead of from a file. The code compiles but nothing happens:

import java.io.*;
import org.xml.sax.*;

public class BandReader extends HandlerBase
{
public static void main(String[] args) throws Exception
{
System.out.println("Here we go ...");
BandReader readerObj = new BandReader();
readerObj.read();
}

public void read () throws Exception
{
String s = &quot;<?xml version='1.0'?><bands><name></name></bands>&quot;;

Parser parserObj = new com.jclark.xml.sax.Driver();

StringReader reader = new StringReader(s);
InputSource source = new InputSource(reader);
parserObj.parse(source);


}

public void startDocument() throws SAXException
{
System.out.println(&quot;Starting ...&quot;);
}

public void endDocument() throws SAXException
{
System.out.println(&quot;... Finished&quot;);
}

public void startElement(String name, AttributeList atts)
throws SAXException
{
System.out.println(&quot;Element is &quot; + name);
}
}


 
Ok, I don't know if it's 'wise' to do it this way, but this is how I figured it out:
(I used class that extended from DefaultHandler and
XMLReader in parsing)

private InputStream getInputSource(String s)
{
PipedOutputStream pos = null;
PipedInputStream pis = null;

try
{
pos = new PipedOutputStream();
pis = new PipedInputStream(pos);
PrintWriter pw = new PrintWriter(pos);

pw.println(s);
pw.close();
}
catch(IOException ioe)
{
System.out.println(ioe.toString());
}
return pis;
}
}

Try to add this method to your program, it returns InputStream that can be used as InputSource.
... And in your method:

InputSource is = new InputSource(getInputSource());
xmlReader.parse(is);
 
Of course:
InputSource is = new InputSource(getInputSource(SomeString));
;)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top