Search This Blog

Tuesday, December 24, 2013

SelectSingleNode C# XML Example

C# > XML > SelectSingleNode

SelectSingleNode selects the first node that matches the XPath expression.

Example

Select node based on attribute value

Products.xml

xml version='1.0'?>
<products xmlns="urn:products-schema">
  <product name="Product1">
    <price>100</price>
  </product>
  <product name="Product2">
    <price>200</price>
  </product>
</products>

C# Code

XmlDocument doc = new XmlDocument();
doc.Load(@"D:\Products.xml");

XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("pp", "urn:products-schema");

XmlElement root = doc.DocumentElement;
XmlNode product = root.SelectSingleNode("pp:product[@name='Product1']", nsmgr);