Wednesday 22 April 2009

Simple Java XML Tag Value Extractor

This Java method is a simple routine to extract values from a simple xml message. It is not a replacement for XPath, which is much more fundamental.

The requirement for this method arose when I had to extract a couple of tags from small xml files, that weren't actually xml! As XPath is pretty strict it couldn't be used as the files wouldn't compile successfully.

So we have "simpleGetTagValue", which accepts the xml and the tag as Strings.

private static String simpleGetTagValue(String xml, String tag) {
String tagValue = new String();
StringBuilder startTag = new StringBuilder("<").append(tag).append(">");
StringBuilder endTag = new StringBuilder("");
int startIndex = xml.indexOf(startTag.toString());
int endIndex = xml.indexOf(endTag.toString());
if(startIndex!=-1 && endIndex !=-1)
tagValue = xml.substring(startIndex+(startTag.length()), endIndex);
return tagValue;
}


Done.

1 comment:

venugopal said...

Thank you for posting such a useful, impressive and a wicked article./Wow.. looking good!

Extractors