Visual Basic 2005 XML Programming Using XML DOM - Loading/Searching an XML document with XML DOM using Visual Basic.NET
(Page 3 of 6 )
The starting point for learning 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 XmlDocument
doc = New XmlDocument
doc.Load(XMLDOCFILEPATH)
In the above code, I am creating a new XMLDocument object and loading XML into it. Make sure that you import "System.XML" before you work on XML-related classes.
Once the XML is loaded into the "XMLDocument" object, we can mold it to any kind of object. For instance, we can create a strongly typed data table using the following code:
Dim nEmps As XmlNodeList = doc.SelectNodes("//Employee")
Dim dt As New DataTable
dt.Columns.Add("ID")
dt.Columns.Add("Empno")
dt.Columns.Add("Ename")
dt.Columns.Add("Sal")
dt.Columns.Add("Deptno")
For Each nEmp As XmlElement In nEmps
Dim dr As DataRow = dt.NewRow
dr("ID") = nEmp.GetAttribute("ID")
dr("Empno") = nEmp.ChildNodes(0).InnerText
dr("Ename") = nEmp.ChildNodes(1).InnerText
dr("Sal") = nEmp.ChildNodes(2).InnerText
dr("Deptno") = nEmp.ChildNodes(3).InnerText
dt.Rows.Add(dr)
Next
The alternative way to achieve something similar to the above is by using "Dataset.ReadXml."
If you observe the above code snippet, I used "//Employee" to retrieve only "Employee" elements (along with their child elements). "//Employee" is an XPath expression. XPath is a simple "search" kind of technology for XML. It has its own operators and syntax. By using XPath expressions we can retrieve/find any part of the provided XML.
Let us consider finding single employee information (using XPath) based on the employee number provided. The following is the code:
Dim nEmp As XmlElement = doc.SelectSingleNode("//Employee[Empno='1007']")
Once the employee is found, we can retrieve information about its child elements as follows:
a = nEmp.SelectSingleNode("Ename").InnerText
b = nEmp.SelectSingleNode("Sal").InnerText
c = nEmp.SelectSingleNode("Deptno").InnerText
d = nEmp.GetAttribute("ID")
Next: Adding, Updating and Deleting From the XML Document with XML DOM Using Visual Basic.NET >>
More Windows Scripting Articles
More By Jagadish Chaterjee