• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 595
  • Last Modified:

Load XML, Find a node, change value

in vb.net how can i load an xml document from a file, go to a node, change its value and save it to a new name.
0
vinny45
Asked:
vinny45
1 Solution
 
grayeCommented:
Here is a VB.Net 2005 example that I use to alter values in an application's config file.  It may be overkill for what you're asking, but what the heck...

' Add a Reference to System.Configuration
Imports System.Configuration
Imports System.xml
Imports System.IO
Imports System.Text

'
' Allows for the editing of key/value pairs in the config file.  This required
' because the My.Settings values are read only.
' Note: You can only change a value, you can not add or delete a key
'
Public Class ConfigXML

    Private cfg As Configuration
    Private xd_app, xd_user As XmlDocument
    Private AssemblyName As String

    Public Enum Section As Integer
        Application = 0
        User
    End Enum

    '
    ' The default constructor loads the configuration file from the
    ' currently running application
    '
    Public Sub New()
        cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        AssemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName.Name

        LoadSections()
    End Sub

    '
    ' Load the configuration file for some other application
    '
    Public Sub New(ByVal ExePath As String, ByVal ExpectedAssemblyName As String)
        Dim map As New ExeConfigurationFileMap
        Dim s As ConfigurationSectionGroup

        If File.Exists(ExePath) Then
            map.ExeConfigFilename = ExePath.Replace(".exe", ".exe.config")
            cfg = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None)

            ' Get the Assembly name from the config file
            s = cfg.SectionGroups("applicationSettings")
            If IsNothing(s) Then
                Throw New ApplicationException("Configuration file missing, corrupt, or not the correct version")
                Exit Sub
            End If
            AssemblyName = s.Sections(0).SectionInformation.Name.Split("."c)(0)
            If AssemblyName <> ExpectedAssemblyName Then
                Throw New ApplicationException("Incorrect Configuration file" & vbCr & "Expecting configuration for " & ExpectedAssemblyName & ", however the configuration file is for " & AssemblyName)
            End If
        Else
            Throw New System.IO.FileNotFoundException
        End If

        LoadSections()
    End Sub

    '
    ' Save the changes back to the config file
    '
    Public Sub SaveSettings()
        Dim sec_app, sec_user As ConfigurationSection
        Dim sb As StringBuilder
        Dim xws As XmlWriterSettings
        Dim xw As XmlWriter

        ' Create settings for the XmlWriter to match the formatting of
        ' the *.config file
        xws = New XmlWriterSettings
        xws.Indent = True
        xws.IndentChars = "    "
        xws.OmitXmlDeclaration = True

        ' prep the XmlWriter
        sb = New StringBuilder
        xw = [XmlWriter].Create(sb, xws)
        If Not IsNothing(xd_app) Then
            xd_app.Save(xw)

            ' replace the entire applicationSettings section
            sec_app = CType(cfg.GetSection("applicationSettings/" & AssemblyName & ".My.MySettings"), ConfigurationSection)
            sec_app.SectionInformation.SetRawXml(sb.ToString)
        End If

        ' do it again for the userSettings section
        sb = New StringBuilder
        xw = [XmlWriter].Create(sb, xws)
        If Not IsNothing(xd_user) Then

            xd_user.Save(xw)
            sec_user = CType(cfg.GetSection("userSettings/" & AssemblyName & ".My.MySettings"), ConfigurationSection)
            sec_user.SectionInformation.SetRawXml(sb.ToString)
        End If

        ' save the changes to the config file
        cfg.Save()
    End Sub

    '
    ' Get a value from a key/value pair from the configuration file
    '
    Public Function GetValue(ByVal Sec As Section, ByVal Key As String) As String
        Dim xn As XmlNode

        xn = Nothing

        ' Use XPath navigation to find the proper node
        Select Case Sec
            Case Section.Application
                If IsNothing(xd_app) Then
                    Return Nothing
                End If
                xn = xd_app.SelectSingleNode("//setting[@name=""" & Key & """]")
            Case Section.User
                If IsNothing(xd_user) Then
                    Return Nothing
                End If
                xn = xd_user.SelectSingleNode("//setting[@name=""" & Key & """]")
        End Select

        If Not IsNothing(xn) Then
            ' is this a serialized string array?
            If xn.InnerXml.StartsWith("<value><ArrayOfString") Then
                Return XMLStringArraytoString(xn.InnerXml.Substring(7, xn.InnerXml.Length - 15))
            End If
            Return xn.InnerText
        End If

        Return Nothing
    End Function

    '
    ' Set a value in the key/value pair of the configuration file
    '
    Public Sub SetValue(ByVal Sec As Section, ByVal key As String, ByVal value As String)
        Dim xn As XmlNode

        xn = Nothing

        ' Use XPath navigation to find the proper node
        Select Case Sec
            Case Section.Application
                If IsNothing(xd_app) Then
                    Exit Sub
                End If
                xn = xd_app.SelectSingleNode("//setting[@name=""" & key & """]")
            Case Section.User
                If IsNothing(xd_user) Then
                    Exit Sub
                End If
                xn = xd_user.SelectSingleNode("//setting[@name=""" & key & """]")
        End Select

        If Not IsNothing(xn) Then
            If value.Contains(vbCr) Then
                ' We make the assumption that if there is an imbedded CR
                ' in the string, then the value is really a string array
                xn.InnerXml = "<value>" & vbCr & String2XMLStringArray(value) & vbCr & "        </value>"
            Else
                xn.InnerXml = "<value>" & value & "</value>"
            End If
        End If
    End Sub

    '
    ' Load the two XML documents with the appropriate section
    '
    Private Sub LoadSections()
        Dim sec_app, sec_user As ConfigurationSection

        ' get the applicationSettings section
        sec_app = CType(cfg.GetSection("applicationSettings/" & AssemblyName & ".My.MySettings"), ConfigurationSection)
        If Not IsNothing(sec_app) Then
            ' make an XmlDocument out of that section
            xd_app = New XmlDocument
            xd_app.LoadXml(sec_app.SectionInformation.GetRawXml)
        End If

        ' do it again for the userSettings section
        sec_user = CType(cfg.GetSection("userSettings/" & AssemblyName & ".My.MySettings"), ConfigurationSection)
        If Not IsNothing(sec_user) Then
            ' make an XmlDocument out of that section
            xd_user = New XmlDocument
            xd_user.LoadXml(sec_user.SectionInformation.GetRawXml)
        End If
    End Sub

    '
    ' Convert an XML serialized string array into a string
    '
    Private Shared Function XMLStringArraytoString(ByVal buf As String) As String
        Dim xmls As Serialization.XmlSerializer
        Dim sr As StringReader
        Dim temp() As String

        ' build a serializer that handles string arrays
        xmls = New System.Xml.Serialization.XmlSerializer(GetType(String()))

        ' do the deed
        sr = New StringReader(buf)
        temp = CType(xmls.Deserialize(sr), String())
        If temp.Length = 0 Then
            Return ""
        End If

        Return Join(temp, vbCrLf)
    End Function

    '
    ' Convert a string array into an XML serialized string
    '
    Private Shared Function String2XMLStringArray(ByVal buf As String) As String
        Dim xmls As Serialization.XmlSerializer
        Dim sb As StringBuilder
        Dim xw As XmlWriter
        Dim xws As XmlWriterSettings
        Dim temp() As String

        ' build a string array
        temp = buf.Split(vbCr.ToCharArray)
        For i As Integer = 0 To UBound(temp)
            temp(i) = temp(i).Trim(vbLf.ToCharArray)
        Next

        ' setup the formatting options
        xws = New XmlWriterSettings
        xws.Indent = True
        xws.IndentChars = "    "
        xws.OmitXmlDeclaration = True

        ' prep the XmlWriter
        sb = New System.Text.StringBuilder
        xw = System.Xml.XmlWriter.Create(sb, xws)

        ' build a serializer that handles string arrays
        xmls = New System.Xml.Serialization.XmlSerializer(GetType(String()))

        ' do the deed
        xmls.Serialize(xw, temp)

        ' add a bit of padding to each line
        temp = sb.ToString.Split(vbCr.ToCharArray)
        For i As Integer = 0 To UBound(temp)
            temp(i) = "            " & temp(i).Trim(vbLf.ToCharArray)
        Next

        Return Join(temp, vbCr)
    End Function
End Class


0
 
manchCommented:
U Can use the function for handling XML (writing a value to XML)
[ And make changes as desired by u ]

    '---------------------------------------------------------------------------------------
    'SetKeyValue
    '---------------------------------------------------------------------------------------
    Public Function SetKeyValue(ByVal Path As String, ByVal KeyName As String, _
                                        ByVal KeyValue As String) As Boolean
        '---------------------------------------------------------------------------------------
        'Function Name  :   SetKeyValue()
        'Purpose        :   Writes the KeyVale to specified Key (KeyName)
        '                   in the Specifile File  (XML)        
 'Return Type    :   True (If Successfully Written) /False (On Error)
        '---------------------------------------------------------------------------------------

        Dim pObjXMLDocument As XmlDocument
        Dim pObjXMLNode As XmlNode
        Dim pObjXMLRoot As XmlNode
        Dim pObjXMLKey As XmlNode
        Dim pObjXMLValue As XmlNode
        Dim pbReturn As Boolean

        Try

            pbReturn = True

            pObjXMLDocument = New XmlDocument

            'Loading the XML File
            pObjXMLDocument.Load(Path)

            pObjXMLNode = pObjXMLDocument.DocumentElement.SelectSingleNode("/configuration/appSettings/add[@key=""" & KeyName & """]")

            'If the Key Not Found
            'Creating It
            If (pObjXMLNode Is Nothing) Then

                'The node does not exist, let's create it
                pObjXMLNode = pObjXMLDocument.CreateNode(XmlNodeType.Element, "add", "")

                'Adding the Key attribute to the node, keep in mind, Xml tokens are case sensitive
                'We should use 'key' instead of 'Key'

                pObjXMLKey = pObjXMLDocument.CreateNode(XmlNodeType.Attribute, "key", "")
                pObjXMLKey.Value = KeyName
                pObjXMLNode.Attributes.SetNamedItem(pObjXMLKey)

                'Adding the key value, once again, remember that Xml tokens are case sensitive

                pObjXMLValue = pObjXMLDocument.CreateNode(XmlNodeType.Attribute, "value", "")
                pObjXMLValue.Value = KeyValue
                pObjXMLNode.Attributes.SetNamedItem(pObjXMLValue)

                'Add the new node to the root
                pObjXMLRoot = pObjXMLDocument.DocumentElement.SelectSingleNode("/configuration/appSettings")

                If (Not (pObjXMLRoot Is Nothing)) Then
                    pObjXMLRoot.AppendChild(pObjXMLNode)
                Else
                    pbReturn = False
                End If

            Else
                '
                'The node exist, save the new value
                pObjXMLNode.Attributes.GetNamedItem("value").Value = KeyValue


            End If

            pObjXMLDocument.Save(AppConfigPath)

            Return pbReturn

        Catch ex As Exception

            pbReturn = False
            Return pbReturn

        Finally

            If (Not (pObjXMLDocument Is Nothing)) Then pObjXMLDocument = Nothing
            If (Not (pObjXMLKey Is Nothing)) Then pObjXMLKey = Nothing
            If (Not (pObjXMLNode Is Nothing)) Then pObjXMLNode = Nothing
            If (Not (pObjXMLRoot Is Nothing)) Then pObjXMLRoot = Nothing
            If (Not (pObjXMLValue Is Nothing)) Then pObjXMLValue = Nothing

        End Try

    End Function
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now