我正在尝试熟悉使用C#解析XML文档。我的XML文件如下所示:
<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";
}
}
我得到的错误是“Null Reference Exception”,如下所示:
var id = Convert.ToInt32(element.Attribute("id").Value);
这几乎就像我在那时尝试访问错误的元素一样,因为似乎属性id
不存在。如果是这种情况,我需要做些什么来修复我的代码?我只是想在XML文件中打印每个资源的信息。
答案 0 :(得分: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
稍快一些。