LINQ to XML Programming Using Visual Basic.NET 2008 - Loading/Searching XML document with LINQ to XML using Visual Basic 2008
(Page 2 of 6 )
The starting point to learn LINQ to XML programming is to load the XML document into an object. Let us look at that:
Const XMLDOCFILEPATH As String = "....MyData.xml"
Dim doc As XDocument
doc = XDocument.Load(XMLDOCFILEPATH)
In the above code, I am creating a new XDocument object and loading XML into it. The XDocument class is completely different from the XMLDocument class. XDocument belongs to the "System.Linq" family whereas "XMLDocument" belongs to the "System.XML" family. Make sure that you import "System.Linq" before you work on "LINQ to XML" related classes.
Once the XML is loaded into the "XDocument" object, we can mold it to any kind of strongly typed object collection, simply by using "LINQ to XML Queries." For instance, the following would parse through all of the XML and give out a "List" based strongly typed collection with exactly the structure we need (Employee Information in this case):
Dim qList = From xe In doc.Descendants.Elements("Employee") _
Select New With { _
.ID = xe.Attribute("ID").Value, _
.Empno = xe.Element("Empno").Value, _
.Ename = xe.Element("Ename").Value, _
.Sal = xe.Element("Sal").Value, _
.Deptno = xe.Element("Deptno").Value _
}
Me.DataGridView1.DataSource = qList.ToList
If you observe the above code snippet, it is pretty similar to SQL querying. However, the above queries an XML Document!
Let us consider finding information on a single employee based on the employee number provided. The following is the code:
Dim qEmp = (From xe In doc.Descendants.Elements("Employee") _
Where xe.<Empno>.Value = "1010" _
Select New With { _
.ID = xe.@ID, _
.Empno = xe.<Empno>.Value, _
.Ename = xe.<Ename>.Value, _
.Sal = xe.<Sal>.Value, _
.Deptno = xe.<Deptno>.Value _
}).FirstOrDefault
In the above code, I wrote a different kind of query which directly uses the XML kind of syntax in Visual Basic itself. This is another great possibility in Visual Basic 2008. You can also observe that I injected a "Where" clause in the "From" statement.
Once the employee is found, we can retrieve information on its child elements as follows:
a = qEmp.SelectSingleNode("Ename").InnerText
b = qEmp.SelectSingleNode("Sal").InnerText
c = qEmp.SelectSingleNode("Deptno").InnerText
d = qEmp.GetAttribute("ID")
Next: Adding, Updating and Deleting from an XML document using LINQ to XML >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee