Wednesday, November 17, 2010

Generic XML Parsing Method

Vinay  Guntaka
Java Programmer


import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ParseXML {
public Map<List<String>,Integer> parseXMLData(String xmlData,String rootTag,List<String> childTags)
{
Map<List<String>, Integer > xmlMap = new HashMap<List<String>,Integer>();

try {

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlData)));
NodeList nodeLst = document.getElementsByTagName(rootTag);
for (int s = 0; s < nodeLst.getLength(); s++) {
List<String> subItems = new ArrayList<String>();
for (int count = 0; count < childTags.size(); count++) {
Node fstNode = nodeLst.item(s);
if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
Element fstElmnt = (Element) fstNode;
NodeList fstNmElmntLst = fstElmnt.getElementsByTagName(childTags.get(count));
Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
NodeList fstNm = fstNmElmnt.getChildNodes();
subItems.add(((Node) fstNm.item(0)).getNodeValue());
}
}
xmlMap.put(subItems, s);
}
} catch (SAXParseException err) {
System.out.println("** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());

} catch (SAXException e) {
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();

} catch (Throwable t) {
t.printStackTrace();
}
return xmlMap;
}
public static void main(String[] args) {
ParseXML p = new ParseXML();
String xmlData = "<data><row><Attribute_Name>java</Attribute_Name><VALUE>5656</VALUE><Child_Name>kids</Child_Name></row>"+
"</data>";
String rootTag = "row";
List<String> tagList = new ArrayList<String>();
tagList.add("Attribute_Name");
tagList.add("VALUE");
tagList.add("Child_Name");
Map<List<String>,Integer> myData = p.parseXMLData(xmlData, rootTag, tagList);
System.out.println(myData);
}
}

No comments:

Post a Comment

Java 1.7 New Features Over 1.6

Automatic Resource Management Description: A proposal to support scoping of resource usage in a block with automatic resource cleanup. T...