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

How we can Use the XMLDocument Class in VB.Net

Author: DevASP
Download Source Code : 571_Use Xml in Vb.Net.zip

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

                    Me.LoadAndDisplayXML()

                Case CMD_LOAD_XML_STRING

                    Me.LoadXMLFromString()

                Case CMD_TEST_FOR_CHILD_NODES

                    Me.HasAnyChildren()

                Case CMD_ITERATE_ALL_NODES

                    Me.IterateThroughNodes()

                Case CMD_DETERMINE_NODE_TYPE

                    Me.DetermineNodeType()

                Case CMD_LIST_ALL_ELEMENT_NODES

                    Me.ListElementNodes()

                Case CMD_LIST_ELEMENTS_BY_TAG

                    Me.ListSpecificTag()

                Case CMD_SELECT_NODES

                    Me.CreateNodeList()

                Case CMD_SELECT_NODE

                    Me.ReferToNode()

                Case CMD_NAVIGATE_RELATED_NODES

                    Me.NavigateToNodes()

                Case CMD_RETRIEVE_ATTRIBUTES

                    Me.RetrieveAttributes()

                Case CMD_CREATE_XML

                    Me.CreateXML()

                Case CMD_ADD_OR_DELETE_ELEMENTS

                    Me.AddDeleteNode()

                Case CMD_ADD_OR_DELETE_ATTRIBUTES

                    Me.AddDeleteAttribute()

                Case CMD_MODIFY_ELEMENT

                    Me.ModifyElementValue()

                Case CMD_MODIFY_ATTRIBUTE

                    ModifyAttributeValue()

                Case CMD_VALID_XML

                    Me.CheckIfXMLValid()

                Case CMD_PARSE_ERRORS

                    Me.GetXMLErrorDetail()

            End Select

 

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

          msw.Flush()

          msw.Close()

        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

 

        xDoc.Load(mstrModifyFile)

 

        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

                xElmntFamily.RemoveChild(xNode)

            Next

            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.Attributes.RemoveNamedItem("age")

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

            End If

            xDoc.Save(mstrModifyFile)

            Me.txtXMLEdits.Text = xDoc.OuterXml

        Else

            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.

Article Comments
I am transferring code from vb6 to vb.net and don't kow how to set the property on an XML Document using system.xml. Here's the statement in vb6:
xmlDoc.setProperty "ServerHTTPRequest", True

How do I do this using vb.net and
Import system.xml

Posted on 11/3/2010 1:41:55 PM by Sam Bitter

How do I xmldoc.setproperty using .net framework and vb.net? setporperty is not a valid parameter.

Posted on 11/3/2010 1:44:32 PM by Sam Bitter

How do I xmldoc.setproperty using .net framework and vb.net? setporperty is not a valid parameter.

Posted on 11/3/2010 2:15:08 PM by Sam Bitter

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< Working with Enterprise Services Components using VB.Net. (Part 2)

Disclaimer - Privacy
© 2002-2017 DevASP.net