2011-08-03 22 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"); 
         } 
        } 
       } 

を取得します。誰かが私が間違っていた場所を知ることができますか?

+0

NULLPointerExceptionが発生している行はありますか? – Dimitri

+0

NodeList subcatLst = cat.getChildNodes(); – RAAAAM

+0

@HariRam、デバッグしましたか(デバッガを使用して)何がnullであるかを確認しましたか? –

答えて

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; 
} 

あなたは、例えば、クラスでこれを置く場合

Element subCategoryAndroid = DOMUtil.getElementByNameAttribute("subcategory", "android", doc); 

PS:これはテストされDOMUtilは(私の場合)は、単にこれを行うことができます。

関連する問題