2014-01-21 43 views
0

我想熟悉用C#解析XML文檔。我的XML文件是這樣的:解析這個XML時出現空引用異常(包含C#代碼)

<title> 
    <titledata titletype="standard"> 
    <currentid>18097</currentid> 
    </titledata> 
    <resourcedata> 
    <resource id="36" resourcetype="image"> 
     <name>nextBtn.gif</name> 
     <relativelink>images/nextBtn.gif</relativelink> 
     <resourceflags>0</resourceflags> 
     <lastupdated>1367612131</lastupdated> 
    </resource> 
    <resource id="37" resourcetype="image"> 
     <name>nextOver.gif</name> 
     <relativelink>images/nextOver.gif</relativelink> 
     <resourceflags>0</resourceflags> 
     <lastupdated>1367612131</lastupdated> 
    </resource> 
    <resource id="38" resourcetype="image"> 
     <name>nextDown.gif</name> 
     <relativelink>images/nextDown.gif</relativelink> 
     <resourceflags>0</resourceflags> 
     <lastupdated>1367612131</lastupdated> 
    </resource> 
    <resourcedata> 
</title> 

我的代碼如下所示:

private void button1_Click(object sender, EventArgs e) 
    { 
     var ofd = new OpenFileDialog { Filter = "XML|*.xml" }; 
     if (ofd.ShowDialog() != DialogResult.OK) return; 

     var xdoc = XDocument.Load(ofd.FileName); 

     foreach (var element in xdoc.Descendants("resourcedata")) 
     { 
      var id = Convert.ToInt32(element.Attribute("id").Value); 
      var resourceType = element.Attribute("resourcetype").Value; 
      var name = element.Element("name").Value; 
      var relativeLink = element.Element("relativeLink").Value; 
      var resourceFlag = Convert.ToInt32(element.Element("resourcetype").Value); 
      var lastUpdated = Convert.ToInt32(element.Element("lastupdated").Value); 
      resourceFlag, lastUpdated); 

      textBox1.Text += "ID: " + id + "\r\n"; 
      textBox1.Text += "Resource Type: " + resourceType + "\r\n"; 
      textBox1.Text += "Name: " + name + "\r\n"; 
      textBox1.Text += "Relative Link: " + relativeLink + "\r\n"; 
      textBox1.Text += "Resource Flag: " + resourceFlag + "\r\n"; 
      textBox1.Text += "Last Updated: " + lastUpdated + "\r\n"; 

     } 
    } 

我得到的錯誤是 「空引用異常」 上以下行:

var id = Convert.ToInt32(element.Attribute("id").Value); 

這幾乎就像我試圖訪問錯誤的元素,因爲它似乎id屬性不存在。如果是這種情況,我需要做些什麼來修復我的代碼?我只是想打印XML文件中每個資源的信息。

回答

3

foreach源更改爲:

foreach (var element in xdoc.Descendants("resourcedata").Elements("resource")) 

否則你遍歷<resourcedata>元素,沒有屬性命名id

PS。如果文件看起來像你向我們展示了,你可以試試下面還有:

foreach (var element in xdoc.Root.Element("resourcedata").Elements("resource")) 

應比使用Descendants稍快。

+0

啊哈!缺失的一塊。你已經找到它了!非常感謝!計時器一旦啓動,我會標記答案。我讚賞你的幫助! – Kevin