Select XML Nodes by Name or Attribute Value in C#
To locate specific elements within an XML document, XPath expressions are commonly used. The SelectNodes
method of the XmlNode
class retrieves a collection of nodes that match a given XPath query. On the other hand, the SelectSingleNode
method returns only the first node that satisfies the specified XPath condition.
Let’s assume we have the following XML structure as an example.
<Names>
<Name type="M">
<FirstName>Lionel</FirstName>
<LastName>Messi</LastName>
</Name>
<Name type="M">
<FirstName>Cristiano</FirstName>
<LastName>Ronaldo</LastName>
</Name>
<Name type="F">
<FirstName>Maria</FirstName>
<LastName>Sharapova</LastName>
</Name>
</Names>
To retrieve all <Name> elements from an XML document, you can use the XPath query /Names/Name. The leading slash / indicates that the <Names> element must be the root of the XML structure. By calling the SelectNodes method, you’ll receive an XmlNodeList containing all matching <Name> nodes. If you need to access the value of a child element like <FirstName>, you can do so by indexing the parent XmlNode with the tag name—for example: xmlNode[“FirstName”].InnerText. Here’s a sample code snippet to illustrate this approach.
// Create an XmlDocument object and load the XML data
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlData);
// Use XPath to select all <Name> nodes under the root <Names> element
XmlNodeList nameNodes = xmlDoc.SelectNodes("/Names/Name");
// Loop through each <Name> node in the list
foreach (XmlNode nameNode in nameNodes)
{
// Access the <FirstName> and <LastName> child nodes and get their values
string firstName = nameNode["FirstName"]?.InnerText;
string lastName = nameNode["LastName"]?.InnerText;
Console.WriteLine($"First Name: {firstName}, Last Name: {lastName}");
}
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(str); // suppose that str string contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name[@type='M']");
foreach (XmlNode xn in xnList)
{
Console.WriteLine(xn.InnerText);
}