[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Editing a XML file

Posted on 2005-04-18
12
Medium Priority
?
249 Views
Last Modified: 2010-04-23
Yesterday I got help from S-Twilley on how to add, search and delete an element from a XML file. His code listed below. What I forgot to ask is how to edit an element in the XML file. So, let's  say I do a search and it populates the textboxes. I then make my changes and then click an 'Edit' command button which would then save my changes. Another thing I need is if the Server name already exists in the XML file it will let you know so it doesn't add it again.

 Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
        AddServer()
    End Sub

    Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click
        LoadServer(txtSearch.Text)
    End Sub

    Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
        DeleteServer(txtSearch.Text)
    End Sub

    Private Sub cmdEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEdit.Click
        EditServer()
    End Sub

    Sub EditServer()
       'Code needed
    End Sub

    Sub AddServer()
        Dim doc As New XmlDocument
        doc.Load("c:\VB Testing\UMZ\UMZ.xml")

        Dim root As XmlNode = doc.DocumentElement
        Dim EleName As XmlElement = doc.CreateElement("Server")
        Dim ElePreMVS As XmlElement = doc.CreateElement("PreMVS")
        Dim ElePostMVS As XmlElement = doc.CreateElement("PostMVS")
        Dim ElePreCS As XmlElement = doc.CreateElement("PreCS")
        Dim ElePostCS As XmlElement = doc.CreateElement("PostCS")
        Dim EleMisc As XmlElement = doc.CreateElement("Misc")

        EleName.SetAttribute("name", txtName.Text)
        ElePreMVS.InnerText = txtPreMVS.Text
        ElePostMVS.InnerText = txtPostMVS.Text
        ElePreCS.InnerText = txtPreCS.Text
        ElePostCS.InnerText = txtPostCS.Text
        EleMisc.InnerText = txtMisc.Text

        EleName.AppendChild(ElePreMVS)
        EleName.AppendChild(ElePostMVS)
        EleName.AppendChild(ElePreCS)
        EleName.AppendChild(ElePostCS)
        EleName.AppendChild(EleMisc)

        root.AppendChild(EleName)
        doc.Save("c:\VB Testing\UMZ\UMZ.xml")
    End Sub
    Function LoadServer(ByVal desiredServer As String) As Boolean
        Dim doc As New XmlDocument
        doc.Load("c:\VB Testing\UMZ\UMZ.xml")

        Dim root As XmlNode = doc.DocumentElement

        Dim nodeServer As XmlNode
        Dim thisServerName As String
        Dim nodeFound As Boolean = False

        For Each nodeServer In root.ChildNodes
            Try
                thisServerName = nodeServer.Attributes("name").InnerText

                If thisServerName.ToLower = desiredServer.ToLower Then
                    txtName.Text = thisServerName
                    txtPreMVS.Text = nodeServer.SelectSingleNode("PreMVS").InnerText
                    txtPostMVS.Text = nodeServer.SelectSingleNode("PostMVS").InnerText
                    txtPreCS.Text = nodeServer.SelectSingleNode("PreCS").InnerText
                    txtPostCS.Text = nodeServer.SelectSingleNode("PostCS").InnerText
                    txtMisc.Text = nodeServer.SelectSingleNode("Misc").InnerText
                    nodeFound = True
                    Exit For
                End If
            Catch ex As Exception
            End Try
        Next
             Return nodeFound
       
    End Function

    Function DeleteServer(ByVal desiredServer As String) As Boolean
        Dim doc As New XmlDocument
        doc.Load("c:\VB Testing\UMZ\UMZ.xml")

        Dim root As XmlNode = doc.DocumentElement

        Dim nodeServer As XmlNode
        Dim thisServerName As String
        Dim nodeFound As Boolean = False

        For Each nodeServer In root.ChildNodes
            Try
                thisServerName = nodeServer.Attributes("name").InnerText

                If thisServerName.ToLower = desiredServer.ToLower Then
                    nodeFound = True
                    Exit For
                End If
            Catch ex As Exception
            End Try
        Next

        If nodeFound Then
            root.RemoveChild(nodeServer)
            doc.Save("c:\VB Testing\UMZ\UMZ.xml")
        End If

        Return nodeFound
    End Function
0
Comment
Question by:Richard Kreidl
  • 8
  • 4
12 Comments
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13813032
So in your textboxes... if you edit anything other than the servername... it will update the contents of the corresponding node in the xml file?

Also, if you change the servername as well, should it create a new nodeblock since there is no server name with that name (and add the contends as well)
0
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13813359
Ok... here's a method called EditServer

===============================

    Function EditServer(ByVal desiredServer As String, Optional ByVal CreateOnNotFound As Boolean = True) As Boolean
        Dim doc As New XmlDocument

        doc.Load(saveFile)

        Dim root As XmlNode = doc.DocumentElement

        Dim nodeServer As XmlNode
        Dim thisServerName As String
        Dim nodeFound As Boolean = False

        For Each nodeServer In root.ChildNodes
            Try
                thisServerName = nodeServer.Attributes("name").InnerText

                If thisServerName.ToLower = desiredServer.ToLower Then
                    nodeServer.SelectSingleNode("PreMVS").InnerText = txtPreMVS.Text
                    nodeServer.SelectSingleNode("PostMVS").InnerText = txtPostMVS.Text
                    nodeServer.SelectSingleNode("PreCS").InnerText = txtPreCS.Text
                    nodeServer.SelectSingleNode("PostCS").InnerText = txtPostCS.Text
                    nodeServer.SelectSingleNode("Misc").InnerText = txtMisc.Text
                    nodeFound = True
                    Exit For
                End If
            Catch ex As Exception
            End Try
        Next

        If Not nodeFound Then
            AddServer()
        End If

        Return nodeFound
    End Function

============================
0
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13813370
I also changed the doc.load part for all the methods:

Dim saveFile As String = "c:\VB Testing\UMZ\UMZ.xml"

put that line at outside of a method... so it's easy to change

and replace all the:    doc.Load("c:\VB Testing\UMZ\UMZ.xml")
with                          doc.Load(saveFile)

==========================================

Usage:

Ok... if you call the method with:

EditServer(txtName.Text)           => Searches for existing server, if found, it updates, if not... it adds a new one
EditServer(txtName.Text, True)  => As Above
EditServer(txtName.Text, False)  => Searches for existing, if found, it updates, if not, it does nothing

The method always returns whether it edits an existing server

============================================

CORRECTION:

        If (Not nodeFound) AND CreateOnNotFound Then
            AddServer()
        End If
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 12

Expert Comment

by:S-Twilley
ID: 13813378
Was also thinking that when your project loads you should test whether the xml file exists... if it doesnt.. it creates a template.  "<UMZ />"  is all thats needed.

You should probably also put a Try Catch block around the Doc.Load method  or to test whether the file has been removed during execution.
0
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13813609
Also... rather than using the AddServer to add a server... you might find it better to just use the EditServer method... as the AddServer method doesn't check for existing servers... where as using the EditServer method, you can check.
0
 
LVL 2

Author Comment

by:Richard Kreidl
ID: 13814978
S-Twilley, it's not working for some reason, here is all my code:

Dim saveFile As String = "c:\VB Testing\UMZ\UMZ.xml"
   
    Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
        AddServer()
    End Sub
    Private Sub cmdSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSearch.Click
        LoadServer(txtSearch.Text)
    End Sub
    Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
        DeleteServer(txtSearch.Text)
    End Sub
    Private Sub cmdEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEdit.Click
        EditServer(txtSearch.Text)
    End Sub
    Function EditServer(ByVal desiredServer As String, Optional ByVal CreateOnNotFound As Boolean = True) As Boolean
        Dim doc As New XmlDocument

        doc.Load(saveFile)

        Dim root As XmlNode = doc.DocumentElement

        Dim nodeServer As XmlNode
        Dim thisServerName As String
        Dim nodeFound As Boolean = False

        For Each nodeServer In root.ChildNodes
            Try
                thisServerName = nodeServer.Attributes("name").InnerText

                If thisServerName.ToLower = desiredServer.ToLower Then
                    nodeServer.SelectSingleNode("PreMVS").InnerText = txtPreMVS.Text
                    nodeServer.SelectSingleNode("PostMVS").InnerText = txtPostMVS.Text
                    nodeServer.SelectSingleNode("PreCS").InnerText = txtPreCS.Text
                    nodeServer.SelectSingleNode("PostCS").InnerText = txtPostCS.Text
                    nodeServer.SelectSingleNode("Misc").InnerText = txtMisc.Text
                    nodeFound = True
                    Exit For
                End If
            Catch ex As Exception
            End Try
        Next

         If (Not nodeFound) And CreateOnNotFound Then
            AddServer()
        End If

        Return nodeFound
    End Function

    Sub AddServer()
        Dim doc As New XmlDocument
        doc.Load(saveFile)

        Dim root As XmlNode = doc.DocumentElement
        Dim EleName As XmlElement = doc.CreateElement("Server")
        Dim ElePreMVS As XmlElement = doc.CreateElement("PreMVS")
        Dim ElePostMVS As XmlElement = doc.CreateElement("PostMVS")
        Dim ElePreCS As XmlElement = doc.CreateElement("PreCS")
        Dim ElePostCS As XmlElement = doc.CreateElement("PostCS")
        Dim EleMisc As XmlElement = doc.CreateElement("Misc")

        EleName.SetAttribute("name", txtName.Text)
        ElePreMVS.InnerText = txtPreMVS.Text
        ElePostMVS.InnerText = txtPostMVS.Text
        ElePreCS.InnerText = txtPreCS.Text
        ElePostCS.InnerText = txtPostCS.Text
        EleMisc.InnerText = txtMisc.Text

        EleName.AppendChild(ElePreMVS)
        EleName.AppendChild(ElePostMVS)
        EleName.AppendChild(ElePreCS)
        EleName.AppendChild(ElePostCS)
        EleName.AppendChild(EleMisc)

        root.AppendChild(EleName)
        doc.Save(saveFile)
    End Sub
    Function LoadServer(ByVal desiredServer As String) As Boolean
        Dim doc As New XmlDocument
        doc.Load(saveFile)

        Dim root As XmlNode = doc.DocumentElement

        Dim nodeServer As XmlNode
        Dim thisServerName As String
        Dim nodeFound As Boolean = False

        For Each nodeServer In root.ChildNodes
            Try
                thisServerName = nodeServer.Attributes("name").InnerText

                If thisServerName.ToLower = desiredServer.ToLower Then
                    txtName.Text = thisServerName
                    txtPreMVS.Text = nodeServer.SelectSingleNode("PreMVS").InnerText
                    txtPostMVS.Text = nodeServer.SelectSingleNode("PostMVS").InnerText
                    txtPreCS.Text = nodeServer.SelectSingleNode("PreCS").InnerText
                    txtPostCS.Text = nodeServer.SelectSingleNode("PostCS").InnerText
                    txtMisc.Text = nodeServer.SelectSingleNode("Misc").InnerText
                    nodeFound = True
                    Exit For
                End If
            Catch ex As Exception
            End Try
        Next
       Return nodeFound

    End Function

    Function DeleteServer(ByVal desiredServer As String) As Boolean
        Dim doc As New XmlDocument
        doc.Load(saveFile)

        Dim root As XmlNode = doc.DocumentElement

        Dim nodeServer As XmlNode
        Dim thisServerName As String
        Dim nodeFound As Boolean = False

        For Each nodeServer In root.ChildNodes
            Try
                thisServerName = nodeServer.Attributes("name").InnerText

                If thisServerName.ToLower = desiredServer.ToLower Then
                    nodeFound = True
                    Exit For
                End If
            Catch ex As Exception
            End Try
        Next

        If nodeFound Then
            root.RemoveChild(nodeServer)
            doc.Save(saveFile)
        End If

        Return nodeFound
    End Function

I type in an exiting server name in the txtSearch.textbox and click cmdEditServer button and the textboxes don't populate with the data.  Then I tried typing in an existing server and clicking the cmdSearch button which finds the server ok and populates the textboxes. I make my changes to the textboxes and then click cmdEditServer and it doesn't update.

It looks like it should work, but I'm not sure why.
0
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13815098
why would the textboxes populate when you click edit server?  isn't it the case that when you click on edit server... that the xml file is updated with the contents of the textboxes?

to populate data from the xml file and update the textboxes... you use the search button (which uses LoadServer).. which you say works

0
 
LVL 2

Author Comment

by:Richard Kreidl
ID: 13815134
S-Twilley, I think the problem is with this 'if ' statement:

 If (Not nodeFound) AND CreateOnNotFound Then
            AddServer()
        End If

When I removed the 'If' statement and just left AddServer()
 I make my changes and click cmdEditServer and it adds a dup server name.
0
 
LVL 2

Author Comment

by:Richard Kreidl
ID: 13815155
Your right, I click the search button and it populates the textboxes if the servername  exists. I make my changes and click cmdEditServer and it doesn't update.
0
 
LVL 12

Expert Comment

by:S-Twilley
ID: 13815156
The progress of EditServer should be this:

IF SERVER EXISTS IN XML FILE
     UPDATE THAT SERVER WITH VALUES OF TEXTBOXES (txtPreMVS through to txtMisc)

ELSE (if server doesn't exist in file)
     IF USER HAS REQUESTED THAT SERVER SHOULD BE ADDED IF IT DOESNT EXIST
           CREATE SERVER AND USE VALUES OF TEXTBOXES  (txtPreMVS through to txtMisc)
     END IF
END IF
0
 
LVL 12

Accepted Solution

by:
S-Twilley earned 2000 total points
ID: 13815174
What doesn't update? the xml file   or the textboxes?   the textboxes shouldn't update on an editserver...

but i've seen the problem:

within the editserver code:

        For Each nodeServer In root.ChildNodes
            Try
                thisServerName = nodeServer.Attributes("name").InnerText

                If thisServerName.ToLower = desiredServer.ToLower Then
                    nodeServer.SelectSingleNode("PreMVS").InnerText = txtPreMVS.Text
                    nodeServer.SelectSingleNode("PostMVS").InnerText = txtPostMVS.Text
                    nodeServer.SelectSingleNode("PreCS").InnerText = txtPreCS.Text
                    nodeServer.SelectSingleNode("PostCS").InnerText = txtPostCS.Text
                    nodeServer.SelectSingleNode("Misc").InnerText = txtMisc.Text
                    nodeFound = True
                    doc.Save(saveFile)               ' <= WE WERE MISSING THIS LINE... my bad :P
                    Exit For
                End If
            Catch ex As Exception
            End Try
        Next
0
 
LVL 2

Author Comment

by:Richard Kreidl
ID: 13815205
Yep, that was it. Sorry if i'm not being clear on my description of the problem. Thanks again for your quick response.
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question