Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

XML Parser  RSS feed

Nirmala Devi
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

How do I parse an XML, which is stored in a String?
Assume the string name is xmlString. It contains 'employee' as root node and firstname, lasename, address as child node.

I tried the following with xml4J parser.
1. Create a parser object
Parser p = new Parser("parser.err");
2. converting a string into an inputstream.
ByteArrayInputStream is = new ByteArrayInputStream(xmlString.getBytes());

3. Create the DOM tree
TXDocument document = parser.readStream(is);
here, document(DOM tree) is null. So, I am not able to get the root element. Why is that???

William Brogden
Author and all-around good cowpoke
Posts: 13078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should be getting some sort of Exception with useful information as to why it didn't work. With JAXP 1.1, I use a chain of catch statements as follows - where tf is a File object
try {
System.out.println("loadDOM from: " + tf.getAbsolutePath() );
// Jaxp 1.1 style
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating( false );
dbf.setNamespaceAware( false );
dbf.setIgnoringElementContentWhitespace( true );
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse( tf );
}catch( ParserConfigurationException pce){
System.out.println("Parser: " + pce );
}catch(SAXParseException spe ){
StringBuffer sb = new StringBuffer( spe.toString() );
sb.append("\n Line number: " + spe.getLineNumber());
sb.append("\nColumn number: " + spe.getColumnNumber() );
sb.append("\n Public ID: " + spe.getPublicId() );
sb.append("\n System ID: " + spe.getSystemId() + "\n");
String tmp = sb.toString();
System.out.print( tmp );
}catch( SAXException se ){
System.out.println("createDocument threw " + se );
se.printStackTrace( System.out );
author of:
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!