我正在解析xml文件。我总是得到NullPointerException
。任何人都可以建议我在哪里犯了错误?
<?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>
在上面的xml文件中,我只想解析子类别android的名称。为此,我做了
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");
}
}
}
每当我这样做时,我都会NullPointerException
。任何人都可以知道我犯了什么错误吗?
答案 0 :(得分:2)
此代码简化了您尝试实现的目标:
public static Element getElementByNameAttribute(String elementName, String nameAttributeValue, Document doc) {
if (elementName!= null && !elementName.isEmpty() && nameAttributeValue!= null && !nameAttributeValue.isEmpty()) {
NodeList subCategoryList = doc.getElementsByTagName(elementName);
for (int i = 0; i < subCategoryList.getLength(); i++) {
Element element = (Element) subCategoryList.item(i);
if (nameAttributeValue.equals(element.getAttribute("name"))) {
return element;
}
}
}
return null;
}
如果你把它放在一个班级,例如DOMUtil
(在我的情况下),您可以这样做:
Element subCategoryAndroid = DOMUtil.getElementByNameAttribute("subcategory", "android", doc);
PS:这是未经测试的。