Monday, 22 April 2013

How to Select XML Nodes by Attribute Value using XPath expression in C#?

How to Select XML Nodes by Attribute Value using XPath expression in C#?
 
This example shows how to select nodes from XML document by attribute value. Use method XmlNode.SelectNodes to get list of nodes selected by the XPath expression. Suppose we have this XML file.
 
<Names>
    <Name type="M">John</Name>
    <Name type="F">Susan</Name>
    <Name type="M">David</Name>
</Names>
 
To get all name nodes use XPath expression /Names/Name. To get only male names (to select all nodes with specific XML attribute) use XPath expression /Names/Name[@type='M'].
 
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXMLDocPath);  //Path of XML file
XmlNodeList xnList = xml.SelectNodes("/Names/Name[@type='M']");

foreach (XmlNode xn in xnList)
{
  Console.WriteLine(xn.InnerText);
}

 
The output is:
John
David

2 comments:

  1. I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very
    useful and knowledgeable. I would like to thank you for the effort you have made in writing this article.


    edupdf.org

    ReplyDelete
  2. Good day! I was so impressed to see a very well-presented dishes that is absolutely tasty
    and delicious. You've done a great job.Well, thank you for sharing your talent and article
    it is very well appreciated. You can also visit my site if you have time.

    n8fan.net

    www.n8fan.net

    ReplyDelete