I am trying to load a xml file from c# in the code behind of a windows forms application. This is the code I use:
XmlDocument xdoc = new XmlDocument();
xdoc.Load("file.xml");
foreach (XmlNode obj in xdoc.SelectNodes("/enabledobjects/object/*"))
{
RadListDataItem item = new RadListDataItem();
item.Text = obj["objectname"].InnerText;
item.Value = obj["value"].InnerText;
DropDownList.Items.Add(item);
}
When i run debug the program, the I gent no errors. The program starts like it should for a few seconds. Then it carashes and finishes the debugging. Visual Studio shows following message:
The program '[6728] Daten Archivar.vshost.exe: Managed (v4.0.30319)' has exited with code -1073741819 (0xc0000005) 'Access violation'.
I have full administrator privileges. The file is saved in the same folther the exe is saved with full access for everyone. I have no Idea why I cant access it.
The xml file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<enabledobjects>
<object>
<objectname>John</objectname>
<value>Carter</value>
</object>
</enabledobjects>
Ok, this is really a bad mistake. The error occures because the xpath was wrong:
foreach (XmlNode obj in xdoc.SelectNodes("/enabledobjects/object/*"))
{
RadListDataItem item = new RadListDataItem();
item.Text = obj["objectname"].InnerText;
by looping like this, we try with the obj["objectname"].InnerText
to access the "objectname" child of <objectname>John</objectname>
.
The solution to this problems is easy:
foreach (XmlNode obj in xdoc.SelectNodes("/enabledobjects/object"))
{
RadListDataItem item = new RadListDataItem();
item.Text = obj["objectname"].InnerText;
by removing /* we define the <object>
as xmlNode object.
So the access violation was created because the child, we wanted to read out the innerText, never existed. Hope this helps someone sometime.