I am parsing the xml file. I am always getting NullPointerException. Can anyone suggest me where I made a mistake?
<?xml version="1.0"?>
<categories>
<category name="ABC">
<subcategory name="windows"
loc="C://program files"
link="www.sample.com"
parentnode="Mac"/>
<subcategory name="456"
loc="C://program files"
link="http://"
parentnode="ABC"/>
</category>
<category name="XYZ">
<subcategory name="android"
loc="C://program files"
link="www.sample.com"
parentnode="XYZ"/>
<subcategory name="apple"
loc="C://program files"
link="http://abc.com"
parentnode="XYZ"/>
</category>
</categories>
In the above xml file, I want to parse only the subcategory name android. For this, I made
NodeList catLst = doc.getElementsByTagName("category");
for (int i = 0; i < catLst.getLength(); i++) {
Node cat = catLst.item(i);
NamedNodeMap catAttrMap = cat.getAttributes();
Node catAttr = catAttrMap.getNamedItem("name");
if (catName.equals(catAttr.getNodeValue())) { // CLUE!!!
NodeList subcatLst = cat.getChildNodes();
for (int j = 0; j < subcatLst.getLength(); j++) {
Node subcat = subcatLst.item(j);
NamedNodeMap subcatAttrMap = subcat.getAttributes();
Node subCatAttr = subcatAttrMap.getNamedItem("name");
if (subCatfound.equals(subCatAttr.getNodeValue())
&& subcatAttrMap != null) {
Node subcatAttr = subcatAttrMap.getNamedItem(attrName);
list.add(subcatAttr.getNodeValue());
} else {
System.out.println("NULL");
}
}
}
Whenever I do this, I am getting NullPointerException. Can anyone know where I made a mistake?
This code is a simplification of what you’re trying to trying to achieve:
If you put this in a class, e.g.
DOMUtil(in my case), you can simply do this:PS: This is untested.