SelectSingleNode in C#

  • Thread starter Thread starter Guest
  • Start date Start date
Can someone show how to use SelectSingleNode and Xpath expression in C#?

First, you need an Xml Document which contains your XML string:

XmlDocument oXmlDoc = new XmlDocument();
oXmlDoc.LoadXml(<your XML string>);

Then you can get a specific, single node, by specifying a valid XPath
expression - read up on the details of those on the 'Net - tons of
good sites:

This sample would select the one (or the first) node <userdata>,
regardless of where in the Xml Document it's located:

XmlNode oTempNode = oXmlDoc.SelectSingleNode("//userdata");

This second example would select the single or first node <address>,
if it's located (directly) inside the <userdata> block - anywhere in
the document:

XmlNode oTempNode = oXmlDoc.SelectSingleNode("//userdata/address");

And this last sample would select the <city> node, directly inside the
<address> tag, which in turn is exactly under the <root> and the
<userdata> tags:

XmlNode oTempNode =
oXmlDoc.SelectSingleNode("root/userdata/address/city");

There's a ton of ways in which you can specify exactly what you're
looking for - that's the power of XPath, but I can't really give you
all the details here - read up on it, there's a ton of stuff out
there!

Marc
================================================================
Marc Scheuner May The Source Be With You!
Bern, Switzerland m.scheuner(at)inova.ch
 
Back
Top