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?
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.
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.
The nodeValue property is used to get the text value of a node. The getAttribute() method returns the value of an attribute.
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
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With