I'm trying to get familiar with parsing an XML document with C#. My XML file looks like this:
<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>
My code looks like this:
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";
}
}
The error I'm getting is "Null Reference Exception" on the following line:
var id = Convert.ToInt32(element.Attribute("id").Value);
It's almost like I'm trying to access the wrong element at that point, because it seems that the attribute id doesn't exist. If that's the case, what do I need to do to fix my code? I'm just basically wanting to print the information for each resource in the XML file.