2012-06-15 108 views
2

我試圖列出一個XML的所有元素和屬性到兩個單獨的List對象。如何檢查一個對象是否被實例化?

我能夠獲得XML中的所有元素。
但是,當我試圖添加的功能得到每個元素中的所有屬性,我總會遇到System.NullReferenceException: Object reference not set to an instance of an object.

enter image description here 下面請仔細閱讀我的代碼,並建議在那裏我不這樣做是正確的。還是有更好的方法來完成這個?您的意見和建議將不勝感激。

using System; 
using System.Collections.Generic; 
using System.Drawing; 
using System.Windows.Forms; 
using System.Xml; 
using System.IO; 

namespace TestGetElementsAndAttributes 
{ 
    public partial class MainForm : Form 
    { 
     List<string> _elementsCollection = new List<string>(); 
     List<string> _attributeCollection = new List<string>(); 

     public MainForm() 
     { 
      InitializeComponent(); 

      XmlDataDocument xmldoc = new XmlDataDocument(); 
      FileStream fs = new FileStream(@"C:\Test.xml", FileMode.Open, FileAccess.Read); 
      xmldoc.Load(fs); 

      XmlNode xmlnode = xmldoc.ChildNodes[1]; 

      AddNode(xmlnode); 
     } 

     private void AddNode(XmlNode inXmlNode) 
     { 
      try 
      { 
       if(inXmlNode.HasChildNodes) 
       { 
        foreach (XmlNode childNode in inXmlNode.ChildNodes) 
        { 
         foreach(XmlAttribute attrib in childNode.Attributes) 
         { 
          _attributeCollection.Add(attrib.Name); 
         } 

         AddNode(childNode); 
        } 
       } 
       else 
       { 
        _elementsCollection.Add(inXmlNode.ParentNode.Name); 
       } 
      } 
      catch(Exception ex) 
      { 
       MessageBox.Show(ex.GetBaseException().ToString()); 
      } 
     } 
    } 
} 

發佈以及示例XML。

<?xml version="1.0" encoding="UTF-8" ?> 
<DocumentName1> 
    <Product> 
     <Material_Number>21004903</Material_Number> 
     <Description lang="EN">LYNX GIFT MUSIC 2012 1X3 UNITS</Description> 
     <Packaging_Material type="25">457</Packaging_Material> 
    </Product> 
</DocumentName1> 
+1

確保您在childNode.Attributes中具有值不確定是否存在問題,但是 21004903似乎沒有屬性 –

+1

使用調試器查明什麼變量是空的。 –

+1

(不要忘了關閉你的FileStream ...) –

回答

3

你應該是這樣的檢查childNode.Attributes存在:

if (childNode.Attributes != null) 
{ 
    foreach(XmlAttribute attrib in childNode.Attributes) 
    { 
    ... 
    } 
} 
+0

太棒了!我沒有想到這個:)。我的檢查是'if(childNode!= null)'。 – yonan2236

+0

不客氣! –

0

你需要確保childNode.Attributes具有價值,所以加if語句之前

if (childNode.Attributes != null) 
{ 
    foreach(XmlAttribute attrib in childNode.Attributes) 
相關問題