Search XML file for nodes with specific attribute value in .NET 2

Mr. Boy picture Mr. Boy · Jan 24, 2013 · Viewed 60.9k times · Source

I found answers for searching XML nodes using LINQ, but I am limited to C# with .NET 2.

I want to open a single XML file (~50Kb, all simple text) and search for all <Tool> nodes with attribute name having a specific value.

It seems like XmlDocument.SelectNodes() might be what I'm looking for, but I don't know XPath. Is this the right way and if so what would code look like?

Answer

Mehmet Ataş picture Mehmet Ataş · Jan 24, 2013

You can use XPath in XmlDocument.SelectNodes such as: SelectNodes("//ElementName[@AttributeName='AttributeValue']")

Xml Sample:

<root>
    <element name="value1" />
    <element name="value2" />
    <element name="value1" />
</root>

C# Sample:

XmlDocument xDoc = new XmlDocument();
// Load Xml

XmlNodeList nodes = xDoc.SelectNodes("//element[@name='value1']");
// nodes.Count == 2

Here you can find some additional XPath samples