I keep getting errors with this, and can't see what I'm doing wrong.
Here's the code
private void _FixSave_Offline_Load(object sender, EventArgs e)
{
System.Xml.XmlDocument NewGame = new System.Xml.XmlDocument();
NewGame.Load(Application.StartupPath + "//Files//Checks_Offline.xml");
foreach (System.Xml.XmlNode nameNode in NewGame.SelectNodes("//Games//NewGame"))
{
开发者_开发百科listView1.Items.Add(nameNode.Attributes["Name"].InnerText);
}
}
And here is the XML Layout
<Games>
<NewGame>
<Name></Name>
<Check></Check>
<Static></Static>
<Location></Location>
<Start></Start>
<Length></Length>
<FoundBy></FoundBy>
<Verified></Verified>
</NewGame>
Here's is the error I keep getting
and visual studio highlights the following code:
listView1.Items.Add(nameNode.Attributes["Name"].InnerText);
I've tried using not only "//" but also "/" so anything that will fix this will be more than welcome, b/c I can't for the life of me see what I'm doing wrong.
At a glance, you're looking for an attribute with the name of "Name", but there are no attributes on any of the XML elements in your example.
I believe you want the content of the Name node:
foreach (System.Xml.XmlNode nameNode in NewGame.SelectNodes("//Games//NewGame/Name"))
{
listView1.Items.Add(nameNode.Value);
}
You might have to play with the XPath expression a bit, depending on the actual structure of your XML document.
I couldn't see your XML example for some reason, but make sure you are distinguishing between Elements and Attributes
Also, make sure that the attribute/element is spelled "Name" exactly. I believe it is case sensitive.
--
Edit: Now I am able to view your XML, it appears that "Name" is actually an element, rather than an attribute.
Try using the Item property, or the Value property instead of nameNode.Attributes
.
I got it to work. Turns out that I the error was due to virtuallist = true. Tim I modified your code above just a little to get the result I wanted. Here's the code for anyone to use for future ref.
private void _FixSave_Offline_Load(object sender, EventArgs e) { System.Xml.XmlDocument NewGame = new System.Xml.XmlDocument(); NewGame.Load(Application.StartupPath + "//Files//Checks_Offline.xml"); foreach (System.Xml.XmlNode nameNode in NewGame.SelectNodes("//Games//NewGame/Name")) { listView1.Items.Add(nameNode.InnerText); } }
And here's a quick screenshot for the given result.
Hope this helps others as well. Thanks to the above people who commented me on this, and big thanks to Tim.
精彩评论