Wednesday, August 7, 2013

Simple XML parsing

All the beginners have a confusion on using XML parsing methods like Pull, DOM or SAX. Follow the below simple customized method to parser your XML string. No need to use any parsing methods.

String strOutputXML = (Your XML String to parse)

Document objDocument = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(strOutputXML));
objDocument = db.parse(is);
catch (ParserConfigurationException e) 
return null;
catch (SAXException e) 
return null;
catch (IOException e) 
return null;

Document doc = objDocument ;

NodeList objNodeList = doc.getElementsByTagName("rule");
int intRuleCount = objNodeList.getLength();

for(int i=0;i<intRuleCount;i++)
String[] strStarting = strOutputXML.split("<rule id=");
String[] strEnding = strStarting[i+1].split("</rule>");
String strRule = strEnding[0];

NodeList objNodeListItem = doc.getElementsByTagName("item");
int intItemCount = objNodeListItem.getLength();

for(int j=0;j<intItemCount;j++)
strStarting = strRule.split("<item>");
strEnding = strStarting[i+1].split("</item>");
String[] strItems = strEnding[0];

No comments:

Post a Comment