How can I find a specific node in my XML?

Jan W picture Jan W · Apr 5, 2012 · Viewed 88.8k times · Source

I have to read the xml node "name" from the following XML, but I don't know how to do it.

Here is the XML:

<?xml version="1.0" standalone="yes" ?>
  <games>
    <game>
      <name>Google Pacman</name>
      <url>http:\\www.google.de</url>
    </game>
  </games>

Code:

using System.Xml;

namespace SRCDSGUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Application.StartupPath + @"\games.xml");


            XmlElement root = doc.DocumentElement;
            XmlNodeList nodes = root.SelectNodes("//games");

            foreach (XmlNode node in nodes)
            {
                listBox1.Items.Add(node["game"].InnerText);
            }


        }
    }
}

Answer

Krishna picture Krishna · Apr 5, 2012

Maybe try this

XmlNodeList nodes = root.SelectNodes("//games/game")
foreach (XmlNode node in nodes)
{
    listBox1.Items.Add(node["name"].InnerText);
}