2009-11-06

Using LINQ to retrieve XML data

Although it is like "to use a cannon to kill a mosquito", I find using LINQ to read XML has a clear advantage - to read the node like an associative array (like PHP).

I use the following VB example to illustrate:


Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim xml_str As String
xml_str = "<ROOT><FIELD1>VALUE1</FIELD1><FIELD2>VALUE2</FIELD2><FIELD3>VALUE3</FIELD3></ROOT>"
Dim xmltree As System.Xml.Linq.XElement
xmltree = XElement.Load(New System.IO.StringReader(xml_str))
Label1.Text = xmltree.Element("FIELD2").Value
End Sub
End Class



I deliberately use a string to hold the XML content in this example, although the native constructor can be as simple as

Dim xmlTree1 As XElement =
<Root>
 <Child1>1</Child1>
 <Child2>2</Child2>
 <Child3>3</Child3>
</Root>