Presents your JAVA E-NEWSLETTER for November 11, 2002 <-------------------------------------------> QUICK PARSING OF XML Parsing XML is quite a heavy-handed thing to do. Whether you use DOM or SAX, or whether you use one of the wrappers such as JDOM or Dom4J to make things easier by setting up all the code, you will often face a daunting task. However, sometimes it's easier to just view the XML as a formatted string. Suppose we have a FactoryMethod class. Given a potentially large chunk of XML, the class will create an XmlCommandFactory based on the tag in the XML. Where the XmlCommandFactory would expect to have a class called XmlSendCommand, the XML would look like: Send ... megabytes of text ... Rather than setting up a full XML parser, it would be much nicer to just say: String type = XmlStrings.getContent(message, "type"); The simplest implementation of this is: static public String getContent(String xml, String tag) { String openTag = "<"+tag; String closeTag = ""; int startIdx = -1; while( (startIdx = xml.indexOf(openTag)) != -1) { char next = xml.charAt(startIdx + tag.length( ) + 1); if( (next == '>') || Character.isWhitespace(next) ) { break; } } if(startIdx == -1) { return null; } startIdx = xml.indexOf(">", startIdx); if(startIdx == -1) { return null; } int closeIdx = xml.indexOf(closeTag, startIdx); if(closeIdx == -1) { return null; } return xml.substring(startIdx+1, closeIdx); } In this code, we allow for the opening tag to have attributes, and avoid matching a tag that simply starts with the desired tag's name. For example, not finding because we're looking for . We don't, however, allow the tag to be nested in another tag with the same name, and we only get the first instance of the tag. Having a library of String utilities designed for XML allows you to avoid the heavy parsing of XML content when all you want to do is access a minor part. ----------------------------------------