Getting an XML Nodes by its Attribute Value in C#

vishalneeraj-24503
Posted by vishalneeraj-24503 under ASP.NET category on | Points: 40 | Views : 435
We will use method XmlNode.SelectNodes to get list of nodes selected by the XPath expression. Suppose we have this XML file.

To get all name nodes,we will use XPath expression /Names/Name.
To get only male names or to select all nodes with specific XML attribute,we will use XPath expression /Names/Name[@type='M'].
Import System.Xml namespace at the top of code-behind page.

using System.Xml;

string str_xml_node = string.Empty;
str_xml_node = "<Names><Name type='M'>Vishal</Name><Name type='F'>Vaishali</Name><Name type='M'>Neeraj</Name><Name type='M'>Kumar</Name></Names>";
XmlDocument emp = new XmlDocument();
emp.LoadXml(str_xml_node);

//For getting Male values
XmlNodeList xn_list = emp.SelectNodes("/Names/Name[@type='M']");
foreach (XmlNode xn in xn_list)
{
Response.Write(xn.InnerText + "<br/>");
}

//For getting Female values
xn_list = emp.SelectNodes("/Names/Name[@type='F']");
foreach (XmlNode xn in xn_list)
{
Response.Write(xn.InnerText + "<br/>");
}


Output:-
Vishal
Neeraj
Kumar
Vaishali

Comments or Responses

Login to post response