LINQ to XML Programming Using Visual Basic.NET 2008 - How to use XPath expressions in LINQ to XML
(Page 6 of 6 )
Most developers are familiar and comfortable with XPath. However, "LINQ to XML" does not support "XPath" directly. No method in "LINQ to XML" directly supports "XPath." However, Microsoft has provided an alternative way to use "XPath" expressions in "LINQ to XML" using "Extension Methods."
Let us consider that I would like to find all "Employee" elements in the document using XPath and want to use "LINQ to XML" to convert the result to strongly typed objects. This can be easily achieved using the following code:
Imports System.Linq
Imports System.Xml.Linq
Imports System.Xml.XPath.Extensions
Public Class Form2
Const XMLDOCFILEPATH As String = "....MyData.xml"
Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
Dim doc As XDocument = XDocument.Load(XMLDOCFILEPATH)
Dim qList = From xe In doc.XPathSelectElements("//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
End Sub
End Class
You can also find a single employee information using XPath together with "LINQ to XML" as follows:
Private Sub btnSingleEmployee_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSingleEmployee.Click
Dim doc As XDocument = XDocument.Load(XMLDOCFILEPATH)
Dim qEmp = (From xe In doc.XPathSelectElements(String.Format("//Employee[Empno='{0}']", Me.txtEmpno.Text)) _
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 _
} _
).FirstOrDefault
If qEmp Is Nothing Then
MessageBox.Show("Not found")
Else
MessageBox.Show(String.Format("Name: {0}, Sal: {1}, Dept: {2}", qEmp.Ename, qEmp.Sal, qEmp.Deptno))
End If
End Sub
I hope you enjoyed the article and any suggestions, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |