Skip to main content
gamedev.net
🔒 Locked

XML Problem

Started by Kryptus 6 replies 1k views
Original Post
Kryptus
Kryptus
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);
                }
            }


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

The exception is saying that you don't.
神はサイコロを振らない!
Kryptus
Kryptus
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]
3dModelMan
3dModelMan
LOL Your opening tag <supported> does not match the closing tag </support>!
chollida1
chollida1
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
Kryptus
Kryptus
The </support> instead of </supported> isn't the problem. It's just a spelling mistake when I typed it here for gamedev.
Bad Monkey
Bad Monkey
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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.