2011-08-03 25 views
0

我正在解析xml文件。我總是得到NullPointerException。任何人都可以告訴我我犯了什麼錯誤?如何獲取特定格式的XML屬性

<?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

你在哪一行得到NULLPointerException? – Dimitri

+0

NodeList subcatLst = cat.getChildNodes(); – RAAAAM

+0

@HariRam,你調試過(使用調試器)看看什麼是空的? –

回答

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:這是未經測試。