Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
SQL Server

Working with XMLDocument Class using VB.Net

Author: Zunnair

In this article I Will shows how to take advantage of the XMLDocument class built-in to System.Xml.dll. This class exposes the XML Document Object Model, or DOM, which can be used to manipulate XML da

In previous versions of Visual Basic, XML processing support for the DOM was provided by the MSXML COM library. The .NET Framework provides a vast array of functionality that equals and oftentimes exceeds those functions found in earlier versions of MSXML. This sample takes a task-based approach to showing how to use the DOM. A checked listbox control lists a set of 'How do I' options. Selecting one will perform the task. You might wish to add breakpoints to examine the code and comments as it runs.


Double clicking on form generate this event this event actually' Find our where we're running from, Add path to file names Check to make sure files exists,m' test to see if files exist, Load the command text which are defined as constants in the module declaration section. ' Enable the listbox only if all 3 files were found.


Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim strPath As String strPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase

mstrSimpleFile = strPath & "Simple.xml"

      mstrModifyFile = strPath & "New.XML"

      mstrBadFile = strPath & "Bad.xml"

      Dim blnFileNotFound As Boolean = False

Dim strMsg As String = "The file '{0}' was not found. Please place it in the same directory as the application EXE and restart the application."

If Not File.Exists(mstrSimpleFile) Then

MessageBox.Show(String.Format(strMsg, mstrSimpleFile), Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

blnFileNotFound = True

End If

      If Not File.Exists(mstrModifyFile) Then

      MessageBox.Show(String.Format(strMsg, mstrModifyFile), Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

                  blnFileNotFound = True

      End If

      if Not File.Exists(mstrBadFile) Then

                  MessageBox.Show(String.Format(strMsg, mstrModifyFile), Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

                  blnFileNotFound = True

            End If

            With Me.lstCommands.Items

                  .Add(CMD_LOAD_XML_FILE, False)

                  .Add(CMD_LOAD_XML_STRING, False)

                  .Add(CMD_TEST_FOR_CHILD_NODES, False)

                  .Add(CMD_ITERATE_ALL_NODES, False)

                  .Add(CMD_DETERMINE_NODE_TYPE, False)

                  .Add(CMD_LIST_ALL_ELEMENT_NODES, False)

                  .Add(CMD_LIST_ELEMENTS_BY_TAG, False)

                  .Add(CMD_SELECT_NODES, False)

                  .Add(CMD_SELECT_NODE, False)

                  .Add(CMD_NAVIGATE_RELATED_NODES, False)

                  .Add(CMD_RETRIEVE_ATTRIBUTES, False)

                  .Add(CMD_CREATE_XML, False)

                  .Add(CMD_ADD_OR_DELETE_ELEMENTS, False)

                  .Add(CMD_MODIFY_ELEMENT, False)

                  .Add(CMD_ADD_OR_DELETE_ATTRIBUTES, False)

                  .Add(CMD_MODIFY_ATTRIBUTE, False)

                  .Add(CMD_VALID_XML, False)

                  .Add(CMD_PARSE_ERRORS, False)

            End With

                                    Me.lstCommands.Enabled = (Not blnFileNotFound)

End Sub


That function checks Reinitialize the StringWriter which is used to build strings for display in the text boxes on the form. ' Update the status bar with the last run command, Clean up the StringWriter.


Private Sub lstCommands_ItemCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ItemCheckEventArgs) Handles lstCommands.ItemCheck

            If e.NewValue = CheckState.Checked Then

            Me.txtXMLDisplay.Text = String.Empty

                  Me.txtXMLEdits.Text = String.Empty

                  msw = New StringWriter()

            Select Case Me.lstCommands.Items(e.Index).ToString()

                Case CMD_LOAD_XML_FILE


                Case CMD_LOAD_XML_STRING


                Case CMD_TEST_FOR_CHILD_NODES


                Case CMD_ITERATE_ALL_NODES


                Case CMD_DETERMINE_NODE_TYPE


                Case CMD_LIST_ALL_ELEMENT_NODES


                Case CMD_LIST_ELEMENTS_BY_TAG


                Case CMD_SELECT_NODES


                Case CMD_SELECT_NODE




                Case CMD_RETRIEVE_ATTRIBUTES


                Case CMD_CREATE_XML


                Case CMD_ADD_OR_DELETE_ELEMENTS




                Case CMD_MODIFY_ELEMENT


                Case CMD_MODIFY_ATTRIBUTE


                Case CMD_VALID_XML


                Case CMD_PARSE_ERRORS


            End Select


                        Me.sbInfo.Text = "Last run command: " & Me.lstCommands.Items(e.Index).ToString()



        End If

      End Sub


This method will remove all child nodes of the Family node and then re-add them with some attributes. It also shows how to manipulate existing attributes. Search for a particular node. Delete all the nodes created in the previous answer. insert node for each family member: Attributes aren't quite right. Fix up father's. Remove "age" attribute, and change "type" attribute to "father".


Private Sub AddDeleteAttribute()

        Dim xDoc As New XmlDocument




        Me.txtXMLDisplay.Text = xDoc.OuterXml


        Dim xNode As XmlNode

        Dim xElem As XmlElement


        Dim xElmntFamily As XmlElement

        xNode = xDoc.SelectSingleNode("//Family")


        If Not (xNode Is Nothing) Then

            If TypeOf xNode Is XmlElement Then

                xElmntFamily = CType(xNode, XmlElement)

            End If

            For Each xNode In xElmntFamily



            xElem = InsertTextNode(xDoc, xElmntFamily, "Person", "Gerald L. Smith")

            xElem.SetAttribute("type", "parent")

            xElem.SetAttribute("age", "70")


            xElem = InsertTextNode(xDoc, xElmntFamily, "Person", "Sara Ann Smith")

            xElem.SetAttribute("type", "mother")


            xElem = InsertTextNode(xDoc, xElmntFamily, "Person", "Richard Andrew Smith")

            xElem.SetAttribute("type", "son")


            xElem = InsertTextNode(xDoc, xElmntFamily, "Person", "Emily Jean Smith")

            xElem.SetAttribute("type", "daughter")


            xNode = xDoc.SelectSingleNode("//Person[@type='parent']")

            If Not (xNode Is Nothing) Then

                xElem = CType(xNode, XmlElement)


                xElem.SetAttribute("type", "father")

            End If


            Me.txtXMLEdits.Text = xDoc.OuterXml


            Me.txtXMLEdits.Text = String.Format("Family Node was not found. Please try the '{0}' option first.", CMD_CREATE_XML)

        End If

   End Sub

Sample is given When the sample loads, it checks for the existence of three files:

  • Simple.xml
  • New.xml
  • Bad.xml

If any one of the three does not exist, the main UI will be disabled. The files are located in the \bin folder of the project folder. If the files exist, you will be able to chose a set of commands loaded in to a checked listbox control. Simply highlight an item on the list and then change its check box to selected and the command will be executed. Note some of the commands require saving changes out to disk. Make sure you have read/write permissions to the \bin directory.

Add Article Comment:
Name :
Email Address :
Comments :
<< Checking Active Windows of Operating System using

Disclaimer - Privacy
© 2002-2017