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 XML Parser 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 "XML Parser" Watch "XML Parser" New topic

XML Parser

Nirmala Devi

Joined: Jul 31, 2001
Posts: 3

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

Joined: Mar 22, 2000
Posts: 13027
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:
I agree. Here's the link:
subject: XML Parser
It's not a secret anymore!