XML Problem

Started by
6 comments, last by Bad Monkey 18 years, 8 months ago
I am programming with XML in C# with the code below. The problem is I get an "Object reference not set to an instance of an object" error on the MessageBox.Show(chapterNode["name"].Value); line. Why is this? I've been trying to figure it out, but I can't. I can't use the new keyword on the object can I? How can I fix it?

XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load("C:\\Games.xml");
            XmlNodeList categories = xmldoc.SelectNodes("supported/games");

            // Iterate through all the categories
            foreach (XmlNode categoryNode in categories)
            {
                // Get all chapters in the current category.
                XmlNodeList chapters = categoryNode.SelectNodes("game");

                // Loop through all chapters in the current category and add to the string.
                foreach (XmlNode chapterNode in chapters)
                {
                    MessageBox.Show(chapterNode["name"].Value);
                }
            }


Advertisement
Are you sure that in your "Games.xml", the chapter node has a "name"?

The exception is saying that you don't.
神はサイコロを振らない!
Here's the XML source, maybe I've done something wrong?

<?xml version="1.0" encoding="iso-8859-1"?><supported>	<games>		<game name="Battlefield 1942" icon="bf1942.ico"></game>		<game name="Battlefield 2" icon="bf2.ico"></game>	</games></supported>


[Edited by - Kryptus on August 2, 2005 8:03:41 PM]
LOL Your opening tag <supported> does not match the closing tag </support>!
this seems strange -> chapterNode["name"]
why are u using "name" is the value inside an array?
matibee is correct. to be valid xml you can only have one main node. You havent' closed your node yet as your ending tag doesn't match the beginning tag.

Cheers
Chris
CheersChris
The </support> instead of </supported> isn't the problem. It's just a spelling mistake when I typed it here for gamedev.
Your XPath query can be changed to simplify this to a single loop, and casting each "game" element as an XmlElement in the foreach loop allows you to call the GetAttribute method to retrieve "name"...

i.e.

XmlDocument xmldoc = new XmlDocument();xmldoc.Load("C:\\Games.xml");XmlNodeList games = xmldoc.SelectNodes("//supported/games/game");foreach (XmlElement game in games){    MessageBox.Show( game.GetAttribute("name") );}



Not necessarily the most defensive way to code that, but does it achieve what you are trying to do?

The reason your code does not work is because the indexer (ie [] operator) for XmlNode only applies to child nodes that are elements, of which your "game" element has none.

This topic is closed to new replies.

Advertisement