I am trying to parse XML file which is of the form.
<parent tag>
<child tag>
<element key="property1">value</element>
<element key="property2">value</element>
</child tag>
</parent tag>
How can I get the value of the element tag having property1? My code is as follows.
public static ArrayList<String> parseXML(URL url_str,URLConnection conn_str,String root_tag,String child_tag) throws ParserConfigurationException, SAXException, IOException
{
String s = null;
ArrayList <String> List_value=new ArrayList<String>();
DocumentBuilderFactory dbF = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbF.newDocumentBuilder();
Document doc = dBuilder.parse(conn_str.getInputStream());
doc.getDocumentElement().normalize();
System.out.println("Root : "+doc.getDocumentElement());
System.out.println("****************");
NodeList nList= doc.getElementsByTagName(root_tag);
System.out.println("****************");
for (int i = 0; i < nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
NodeList nodelist1 = element.getElementsByTagName(child_tag);
for (int i1 = 0; i1 < nodelist1.getLength(); i1++)
{
Element element1 = (Element) nodelist1.item(i1);
NodeList fstNm = element1.getChildNodes();
s=fstNm.item(0).getNodeValue();
List_value.add(s);
}
for(int c=0;c<List_value.size();c++)
{
System.out.println(List_value.get(c));
}
}
}
return List_value;
}
I am using DOM parser for the same. Kindly help.
Thank you.
This did the job here (DOM + XPath), more documentation here: http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html
Here is a good explanation about xpath and how it works: http://www.xmlplease.com/axis