.NET – XML and XPath

I have been receiving a few requests for my now elderly Delphi XML/XPath examples to be brought into the world of .NET. Similarly, I have seen a lot of newsgroup posts about using XML and XPath expressions, particularly those XPath expressions that can be used to “query” the XML “database”.

The most popular request seems to have been for my “employee” selector demonstration:

It’s a small application that lets you load some XML (employee data) into an XML document. It then lets you fire a handful of XPath expressions at the XML document via the use of the SelectNode methods. It demonstrates selecting specific employees using a combination of conditions; there’s a mixture of XPath that looks at element values and one that looks at an attribute value. I’ve revamped it slightly, noteably I’ve made a few minor changes to bring it into line with current W3C standard (as enforced by .NET’s SelectNodes method).

[code lang=”XML”]
[XML]



Nelson
Roberto
250
40000


Young
Bruce
233
55500



[/code]

[code lang=”C#”]
[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 XML
{
public partial class Form1 : Form
{
XmlDocument doc;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
doc = new XmlDocument();
doc.Load(“employees.xml”);

textBox1.Text = doc.OuterXml;
}

private void handle_xpath(String xPathExpression)
{
XmlNodeList result;
XmlNode root = doc.DocumentElement;

result = root.SelectNodes(xPathExpression);

label1.Text = String.Format(“{0} items returned”, result.Count);

textBox3.Clear();
foreach (XmlNode x in result)
{
textBox3.Text = textBox3.Text + x.OuterXml + Environment.NewLine + Environment.NewLine;
}
}

private void button2_Click(object sender, EventArgs e)
{
handle_xpath(“.//employee”);
}

private void button3_Click(object sender, EventArgs e)
{
handle_xpath(“/employees”);
}

private void button4_Click(object sender, EventArgs e)
{
handle_xpath(“/employees/employee[1]”);
}

private void button5_Click(object sender, EventArgs e)
{
handle_xpath(“/employees/employee[last()]”);
}

private void button6_Click(object sender, EventArgs e)
{
handle_xpath(“/employees/employee[emp_salary>30000 and emp_salary<35000]"); } private void button7_Click(object sender, EventArgs e) { handle_xpath("/employees/employee[emp_salary>30000 and emp_salary<35000 and emp_salary[@currency='UKP']]"); } private void button8_Click(object sender, EventArgs e) { handle_xpath("/employees/employee[emp_salary > 50000]/emp_lastname”);
}

private void button9_Click(object sender, EventArgs e)
{
handle_xpath(textBox2.Text);
}
}
}
[/code]

The source code is available here [60k].

There’s a short 60 second movie of the application in use here [748kb]. Courtesy of TechSmith’s Camtasia.

Technorati Tags: , , , , , , , , ,