Results 1 to 13 of 13

Thread: [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

Threaded View

  1. #1

    Thread Starter
    Registered User nmadd's Avatar
    Join Date
    Jun 2007
    Location
    U.S.A.
    Posts
    1,676

    [VB.NET] XML - Create and Merge Files. Edit, Add and Delete Nodes.

    There have been some posts recently regarding creating, editing, deleting and adding to XML files. I couldn't find a post in the VB.NET CodeBank regarding XML, so I thought I'd use my basic XML skills and contribute this brief post. So here are some very basic ways of working with XML files. These snippets assume you know what XML is and that there is a System.Xml namespace available in the .NET Framework 2.0 designed to manipulate XML files. Reading through the documentation on the System.Xml namespace will greatly help!

    These are the ways that, so far, I have found to work and to be the most simple. I am still learning the System.Xml namespace. If anyone would like to comment on better ways to do something, please let me know!
    I'd be happy to update this post to help everybody.


    Creating an XML File
    Here we'll use the XmlWriter to create a new XML file. This part of working with XML files is fairly straightforward and easy. Here are the steps:
    • Create an XmlWriter
      • This class does just what it sounds like it does. It is a fast, forward-only way to write XML files.
      • Prepare the settings for the writer. In this case, only choosing to indent each element.
    • Write a declaration
      • In the basic form that we are using it, the declaration specifies which version of XML we are using and how it is encoded.
    • Write a comment
    • Write the root element
      • Each XML file can have only one root element. In our case it is the "People" element.
    • Write elements and attributes that contain information about our "Person."
      • Each person elements contain elements that describe that person in greater detail.
      • Each person contains an attribute called "ID" that will help us easier identify the person later.

    VB.NET Code:
    1. ' Set up our XmlWriter settings.
    2. Dim settings as new XmlWriterSettings()
    3. settings.Indent = True
    4.  
    5. ' Initialize the XmlWriter.
    6. Dim XmlWrt As XmlWriter = XmlWriter.Create("C:\XmlTest.xml", settings)
    7.  
    8. With XmlWrt
    9.     ' Write the Xml declaration.
    10.     .WriteStartDocument()
    11.     ' Write a comment.
    12.     .WriteComment("Xml example.")
    13.  
    14.     ' Write the root element.
    15.     .WriteStartElement("People")
    16.  
    17.     ' Start our first person.
    18.     .WriteStartElement("Person")
    19.     ' Give this person the attribute ID of 1.
    20.     .WriteAttributeString("ID", "1")
    21.  
    22.     ' The person nodes.
    23.     .WriteStartElement("Name")
    24.     .WriteString("Bob")
    25.     .WriteEndElement()
    26.  
    27.     .WriteStartElement("Age")
    28.     .WriteString("28")
    29.     .WriteEndElement()
    30.  
    31.     .WriteStartElement("Weight")
    32.     .WriteString("180")
    33.     .WriteEndElement()
    34.     ' The end of this person.
    35.     .WriteEndElement()
    36.  
    37.     ' Next person.
    38.     .WriteStartElement("Person")
    39.     .WriteAttributeString("ID", "2")
    40.  
    41.     .WriteStartElement("Name")
    42.     .WriteString("Julie")
    43.     .WriteEndElement()
    44.  
    45.     .WriteStartElement("Age")
    46.     .WriteString("34")
    47.     .WriteEndElement()
    48.  
    49.     .WriteStartElement("Weight")
    50.     .WriteString("125")
    51.     ' The end of this person.
    52.     .WriteEndElement()
    53.     ' The end of People.
    54.     .WriteEndElement()
    55.  
    56.     ' Close the XmlTextWriter.
    57.     .WriteEndDocument()
    58.     .Close()
    59. End With


    Edit an XML File
    Now that we have an XML file, we can edit it. Bob has turned a year older so we need to change his age. With the XmlDocument class we can get this done.
    • Find Bob with his attribute ID of 1
      • It is very easy to find an individual person using their attribute called "ID" since we created this in our first step.
      • We are using the XPath to find the person with the correct ID.
        • The XPath is a language used to easily traverse through an XML files elements.
    • Change the nodes we want
      • Since we have located Bob's node we can edit any of his child nodes or details. In this case we will edit his second child node (index of 1): his age.
    • Save the document
      • Clearly this is an important point, but it seems to be missed quite often. Don't forget to save!

    VB.NET Code:
    1. ' Load the XmlDocument.
    2. Dim xd As New XmlDocument()
    3. xd.Load("C:\XmlTest.xml")
    4.  
    5. ' Find the node where the Person's attribute ID is 1 using its XPath.
    6. Dim nod As XmlNode = xd.SelectSingleNode("/People/Person[@ID='1']")
    7. If nod IsNot Nothing Then
    8.     ' Since we found Bob's node now we can
    9.     ' change the InnerText of his age node.
    10.     nod.ChildNodes(1).InnerText = "29"
    11. Else
    12.     ' Where did Bob go?
    13.     MessageBox.Show("Couldn't find Bob.", "Where's Bob?", MessageBoxButtons.OK, _
    14.         MessageBoxIcon.Information)
    15. End If
    16.  
    17. ' Save the Xml.
    18. xd.Save("C:\XmlTest.xml")


    Add to an XML File
    There are certainly different approaches to appending elements to an XML file. This is the one that I found easiest to use; particularly when adding an entire Person in our case.
    • Create a string containing the information about the person that we want to add to our XML file
      • At the moment this is, of course, just a string. However, it does hold the information that we want to add to our XML file.
      • Though the XML will look nice if you view it in a browser no matter how it looks as a regular text file, for the sake of keeping it looking nice when viewed in Notepad, the string is formatted as such.
    • Load our file again
    • Create a XmlDocumentFragment
      • This is, again, just what it sounds like. This is a lightweight document fragment that is very useful for inserting nodes into an XML file.
      • Next we set the fragment's InnerXml to our string.
    • Append that fragment to our file
      • Now that we have the node setup we can append this to the end of our XmlDocument.
        • Notice that we get the XML file's root with the DocumentElement property. We don't want to append this outside of the root.
    • Save the document
      • Don't forget to save!

    VB.NET Code:
    1. ' Create our string that holds our new Person information.
    2. Dim cr as String = Environment.Newline
    3. Dim newPerson As String = _
    4.     "<Person ID='3'>" & cr & _
    5.     "    <Name>Tommy</Name>" & cr & _
    6.     "    <Age>62</Age>" & cr & _
    7.     "    <Weight>190</Weight>" & cr & _
    8.     "  </Person>"
    9.  
    10. ' Load the XmlDocument.
    11. Dim xd As New XmlDocument()
    12. xd.Load("C:\XmlTest.xml")
    13.  
    14. ' Create a new XmlDocumentFragment for our document.
    15. Dim docFrag As XmlDocumentFragment = xd.CreateDocumentFragment()
    16. ' The Xml for this fragment is our newPerson string.
    17. docFrag.InnerXml = newPerson
    18. ' The root element of our file is found using
    19. ' the DocumentElement property of the XmlDocument.
    20. Dim root As XmlNode = xd.DocumentElement
    21. ' Append our new Person to the root element.
    22. root.AppendChild(docFrag)
    23.  
    24. ' Save the Xml.
    25. xd.Save("C:\XmlTest.xml")


    Delete an XML Node
    We don't need Bob in our list of People any longer so we can now delete him. You alrealdy found him when we edited him, so we just need to change the code so we delete him instead. Easy!
    • Load the XmlDocument once again
    • Find his node again by using the correct XPath
      • You've done this before so this is no problem!
    • Delete all of his information
      • We have Bob's node. We then get his parent to remove Bob's node and all details using the RemoveChild method.
    • Save the document
      • That's right. Don't forget to save!

    VB.NET Code:
    1. ' Load the XmlDocument.
    2. Dim xd As New XmlDocument()
    3. xd.Load("C:\XmlTest.xml")
    4.  
    5. ' Find Bob's node with the attribute ID of 1
    6. ' using the XPath again.
    7. Dim nod As XmlNode = xd.SelectSingleNode("/People/Person[@ID='1']")
    8. If nod IsNot Nothing Then
    9.     ' Since we found Bob's node, we will remove
    10.     ' it and all of his information.
    11.     nod.ParentNode.RemoveChild(nod)
    12. Else
    13.     ' Where's Bob?
    14.     MessageBox.Show("Couldn't find Bob.", "Where's Bob?", MessageBoxButtons.OK, _
    15.         MessageBoxIcon.Information)
    16. End If
    17.  
    18. ' Save the Xml.
    19. xd.Save("C:\XmlTest.xml")

    Well, that's it for now. There will be more to come on XML. I can't get enough!
    I hope that these basics have helped you begin your journey into VB.NET and XML. You can also find a small application using these snippets attached. Good luck!
    Attached Files Attached Files
    Last edited by nmadd; Jul 16th, 2007 at 03:22 PM. Reason: Updated formatting & some code. Changed title.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width