Finding a Node in an XML String
A common requirement with an XML file is to find a particular node. If you are targeting the .NET framework 3.5 or higher, you can find the node using Linq to XML or by using Lambda expressions.
As with many of my prior XML examples, the XML string is as follows:
<Region name="Fox Valley">
<Area name="Oshkosh" />
<Area name="Appleton" />
The code to find the node for the Milwaukee region is as follows:
// Be sure to set a reference to System.Core and System.Xml.Linq
XElement states = XElement.Load("testXML.xml");
// Using LINQ
var query = from XElement r in states.Descendants("Region")
where r.Attribute("name").Value == "Milwaukee"
foundNode = query.FirstOrDefault();
// Using Lambda expressions
foundNode = states.Descendants("Region").
Where(r => r.Attribute("name").Value ==
‘ Be sure to set a reference to System.Core and System.Xml.Linq
Dim states As XElement = XElement.Load("testXML.xml")
‘ Using LINQ
Dim foundNode As XElement
Dim query = From r As XElement In states…<Region> _
Where r.@<name> = "Milwaukee"
foundNode = query.FirstOrDefault()
‘ Using Lambda expression
foundNode = states…<Region>.Where(Function(r) r.@<name> = _
This code first loads the XML file containing the XML. The next set of code can be done using LINQ or using Lambda expressions. Use either one, but not both. 🙂
The C# code uses the XElement properties and methods. The VB code uses XML literals.
NOTE: The XElement properties and methods work in VB as well.
NOTE: This post was created based on a prior post that included both finding a node and adding new nodes. This post separates the first step to provide a more straightforward example.