Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 620
Mr. Boy Avatar asked Jan 24 '13 12:01

Mr. Boy


People also ask

How do I select a specific node in XML?

Select XML Nodes by Name [C#] To find nodes in an XML file you can use XPath expressions. Method XmlNode. SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.

What are nodes and attributes in XML?

Node TypesElement Node − Every XML element is an element node. This is also the only type of node that can have attributes. Attribute Node − Each attribute is considered an attribute node. It contains information about an element node, but is not actually considered to be children of the element.

What is XML node value?

The nodeValue property is used to get the text value of a node. The getAttribute() method returns the value of an attribute.


2 Answers

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

like image 126
Mehmet Ataş Avatar answered Sep 19 '22 06:09

Mehmet Ataş


think you could do something like that (well, rustic, but you've got the idea), using GetElementsByTagName

var myDocument = new XmlDocument();
myDocument.Load(<pathToYourFile>);
var nodes = myDocument.GetElementsByTagName("Tool");
var resultNodes = new List<XmlNode>();
foreach (XmlNode node in nodes)
{
    if (node.Attributes != null && node.Attributes["name"] != null && node.Attributes["name"].Value == "asdf")
    resultNodes.Add(node);
}
like image 35
Raphaël Althaus Avatar answered Sep 19 '22 06:09

Raphaël Althaus