Finding a set of Nodes in an XML String
In this prior post, I demonstrated how to find a node in an XML string. In this post, I expand on that topic to find a set of nodes. You can then process those nodes as needed in your application. In this example, the set of nodes are displayed in a ComboBox.
If you are targeting the .NET Framework version 3.5 or later, you can use Linq to XML to retrieve a set of nodes. This example using Linq.
Here is the XML we will use in this example:
<States>
<State name="California">
<Regions>
<Region name="San Luis Obispo">
<Area name="Santa Maria" />
<Area name="Seaside" />
</Region>
<Region name="Silicon Valley">
<Area name="San Jose"/>
<Area name="Sunnyvale"/>
</Region>
<Region name="Springfield">
<Area name="Emeryville"/>
<Area name="Hooterville"/>
</Region>
</Regions>
</State>
<State name="Wisconsin">
<Regions>
<Region name="Milwaukee">
<Area name="Mukwanago"/>
<Area name="Germantown"/>
</Region>
<Region name="Fox Valley">
<Area name="Oshkosh" />
<Area name="Appleton" />
</Region>
<Region name="Springfield">
<Area name="Ogdenville"/>
<Area name="Shelbyville"/>
</Region>
</Regions>
</State>
</States>
Starting with a simple example, let’s find the set of all regions and display them in a combo box.
In C#:
// Build a list of region names
var regionElements = doc.Descendants("Region");
var regionEnumeration = regionElements.Select
(r => r.Attribute("name").Value);
List<string> regionList = regionEnumeration.ToList();
regionList.Sort();
// Bind to a ComboBox
comboBox1.DataSource = regionList;
// OR
List<string> regions = doc.Descendants("Region").Select
(r => r.Attribute("name").Value).ToList();
regions.Sort();
comboBox1.DataSource = regions;
In VB:
‘ Build a list of region names
Dim regionElements = doc…<Region>
Dim regionEnumeration = regionElements.Select(Function(r) r.@name)
Dim regionList As List(Of String) = regionEnumeration.ToList
regionList.Sort()
‘ Bind to a ComboBox
ComboBox1.DataSource = regionList
‘ OR
Dim regions As List(Of String) = doc…<Region>.Select _
(Function(r) r.@name).ToList
regions.Sort()
ComboBox1.DataSource = regions
The code first finds the set of region elements. The C# code uses the XElement methods and the VB code uses XML literals.
Only the name of the regions are needed, so the next statement selects the name attribute. Again, the C# code uses the XElement methods and the VB code uses XML literals.
NOTE: You can also use the XElement methods in VB as well.
The enumeration is then converted to a list so it can be sorted and assigned as a DataSource.
The second set of code combines the set of Linq to XML statements into one for a more condensed version of the code.
The result is as follows:
Use this technique any time you need to retrieve a set of nodes from an XML file.
Enjoy.