XML in ADO.NET: XML has become one of the most well known and important technologies for representing data. Regarded by many as the key to interoperability and flexibility across applications and platforms, XML support is embedded deeply into the Microsoft. NET Framework, and especially in to ADO.NET. XML Parser: An XML Parser is a program that read an XML document and extracts the data and data descriptions from the XML parser enables you to programmatically work with an xml document having to manually parse the file.
<?xml version="1.0" encoding="UTF-8" ?> <family> <name gender="Male"> <firstname>Ram</firstname> <lastname>Singh</lastname> </name> <name gender="Female"> <firstname>Dena</firstname> <lastname>Singh</lastname> </name> </family>
To Save file family.xml.
Write these codeImports System.IOImports System.XmlModule ParsingUsingXmlTextReader Sub Main() Dim m_xmlr As XmlTextReader 'Create the XML Reader m_xmlr = New XmlTextReader("D:\family.xml") 'Disable whitespace so that you don't have to read over whitespaces m_xmlr.WhiteSpaceHandling = WhiteSpaceHandling.NONE 'read the xml declaration and advance to family tag m_xmlr.Read() 'read the family tag m_xmlr.Read() 'Load the Loop While Not m_xmlr.EOF 'Go to the name tag m_xmlr.Read() 'if not start element exit while loop If Not m_xmlr.IsStartElement() Then Exit While End If 'Get the Gender Attribute Value Dim genderAttribute = m_xmlr.GetAttribute("gender") 'Read elements firstname and lastname m_xmlr.Read() 'Get the firstName Element Value Dim firstNameValue = m_xmlr.ReadElementString("firstname") 'Get the lastName Element Value Dim lastNameValue = m_xmlr.ReadElementString("lastname") 'Write Result to the Console Console.WriteLine("Gender: " & genderAttribute _ & " FirstName: " & firstNameValue & " LastName: " _ & lastNameValue) Console.Write(vbCrLf) End While 'close the reader m_xmlr.Close() End SubEnd Module
Coding for ParsingUsingXmlDocument:Imports System.IOImports System.XmlModule ParsingUsingXmlDocument Sub Main() Try Dim m_xmld As XmlDocument Dim m_nodelist As XmlNodeList Dim m_node As XmlNode 'Create the XML Document m_xmld = New XmlDocument() 'Load the Xml file m_xmld.Load("D:\family.xml") 'Get the list of name nodes m_nodelist = m_xmld.SelectNodes("/family/name") 'Loop through the nodes For Each m_node In m_nodelist 'Get the Gender Attribute Value Dim genderAttribute = m_node.Attributes.GetNamedItem("gender").Value 'Get the firstName Element Value Dim firstNameValue = m_node.ChildNodes.Item(0).InnerText 'Get the lastName Element Value Dim lastNameValue = m_node.ChildNodes.Item(1).InnerText 'Write Result to the Console Console.Write("Gender: " & genderAttribute _ & " FirstName: " & firstNameValue & " LastName: " _ & lastNameValue) Console.Write(vbCrLf) Next Catch errorVariable As Exception 'Error trapping Console.Write(errorVariable.ToString()) End Try End SubEnd Module
Output:
ADO.NET XML Parser in VB.NET
How to insert Xml Data values into Database