Click here to Skip to main content
15,891,136 members
Articles / Programming Languages / XML

A beginner's guide to XPath

Rate me:
Please Sign up or sign in to vote.
4.11/5 (10 votes)
27 May 2007CPOL5 min read 69.4K   584   53  
This article demonstrates how a beginner can start to get to grips with XPath using C#.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

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

        private void button1_Click(object sender, EventArgs e)
        {
            XmlDocument document = null;
            XmlNodeList nodeList = null;
            XmlNode node = null;

            // Try and load xml data into an Xml document object and throw an
            // error message if this fails
            try
            {
                document = new XmlDocument();
                document.Load("Data.xml");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading 'Data.xml'. Exception: " + ex.Message);
            }

            // If the above was successful...
            if (document != null)
            {
                #region Retrieve a list of book titles
                MessageBox.Show("Starting to list book titles...");
                try
                {
                    // Try and retrieve all book nodes
                    nodeList = document.SelectNodes("/books/book");

                    foreach (XmlNode book in nodeList)
                    {
                        // Show a message with the book title
                        MessageBox.Show(book.SelectSingleNode("title").InnerText);
                    }
                }
                catch (Exception ex)
                {
                    // Error whilst retrieving book data
                    MessageBox.Show("Error whilst retrieving book data. Error message: " + ex.Message);
                }
                MessageBox.Show("Finishing list of book titles...");
                #endregion

            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United Kingdom United Kingdom
I can be contacted via e-mail at francisg04@gmail.com.

My blog can be found at http://csharpcollection.spaces.msn.com.

Comments and Discussions