none
How to Read a Xml File and change it? RRS feed

  • Question

  • hello everybody

    i have a xml file (Progect.exe.config)

    that has values...

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <configSections>
        </configSections>
        <connectionStrings>
            <add name="Person.My.MySettings.ConnectionString" connectionString="Data Source=192.168.0.1;Initial Catalog=Person;User ID=sa;Password=@hghoh159A"
                providerName="System.Data.SqlClient" />
        </connectionStrings>
        <system.diagnostics>
            <sources>
                <!-- This section defines the logging configuration for My.Application.Log -->
                <source name="DefaultSource" switchName="DefaultSwitch">
                    <listeners>
                        <add name="FileLog"/>
                        <!-- Uncomment the below section to write to the Application Event Log -->
                        <!--<add name="EventLog"/>-->
                    </listeners>
                </source>
            </sources>
            <switches>
                <add name="DefaultSwitch" value="Information" />
            </switches>
            <sharedListeners>
                <add name="FileLog"
                     type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
                     initializeData="FileLogWriter"/>
                <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
                <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
            </sharedListeners>
        </system.diagnostics>
    <startup useLegacyV2RuntimeActivationPolicy="true">
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
      </startup>
    </configuration>

    i want get values from this tag

      <connectionStrings>
            <add name="Person.My.MySettings.ConnectionString" connectionString="Data Source=192.168.0.1;Initial Catalog=Person;User ID=sa;Password=@hghoh159A"
                providerName="System.Data.SqlClient" />
        </connectionStrings>


    and change it by this value

      <connectionStrings>
            <add name="Person.My.MySettings.ConnectionString" connectionString="Data Source=192.168.10.1;Initial Catalog=Person;User ID=sa;Password=@tesrt"
                providerName="System.Data.SqlClient" />
        </connectionStrings>


    how to do it?


    Name of Allah, Most Gracious, Most Merciful and He created the human




    • Edited by sh 2020 Friday, August 4, 2017 2:54 PM
    Friday, August 4, 2017 2:51 PM

Answers

  • Hi sh2015,

    Based on your description, you want to modify connection in app.config, please refer to the code below.

      Dim sNewConnStr As String = ""
            Dim xml = XElement.Load("D:\T.xml")
            'Get the first config section (first connection string info)
            Dim connStrXML = xml.Descendants("connectionStrings").Elements().First()
    
            'Get the connection string value
            Dim connStr = connStrXML.Attribute("connectionString").Value
    
            'Create an array with ';'
            Dim arrConn() As String = connStr.Split(";")
    
            For i As Int32 = 0 To arrConn.Length - 1
                'Get the attribute and value splitted by "="
                Dim arrSubConn() As String = arrConn(i).Split("=")
                If (arrSubConn.Length = 2) Then
                    Dim sConnAttr As String = ""
                    Dim sConnValue As String = ""
                    sConnAttr = arrSubConn(0)
                    sConnValue = arrSubConn(1)
    
                    'Change Database name 
                    If (sConnAttr = "Data Source") Then
                        'This is the place where you will be changing the database name 
                        sConnValue = "192.168.10.1"
                    End If
                    If (sConnAttr = "Password") Then
    
                        sConnValue = "@tesrt"
                    End If
    
                    'Generate newly altered connection string
                    sNewConnStr += sConnAttr + "=" + sConnValue + ";"
                End If
            Next
    
            'After doing everything you need To save it back To the same file,
    
            'Modify the existing connection string information
            connStrXML.SetAttributeValue("connectionString", sNewConnStr)
    
            'Saving config at the same place
            xml.Save("D:\T.xml")
            MessageBox.Show("Update successfully!")

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by sh 2020 Monday, August 7, 2017 5:40 PM
    Monday, August 7, 2017 7:29 AM
    Moderator

All replies

  • You will need to read the document, get the connectionStrings node, change the connectionString attribute, and then save the document back to where you initially read it from.

    Here is an example:

    'Read the document
    Dim document As XDocument = XDocument.Load("Progect.exe.config")
    
    'Get the connectionStrings node's connectionString attribute
    Dim connectionString As XAttribute = document.Descendants("connectionStrings").Attributes.SingleOrDefault(Function(a) a.Name = "connectionString")
    
    'Change the value of the attribute
    If connectionString IsNot Nothing Then connectionString.SetValue("Data Source=192.168.10.1;Initial Catalog=Person;User ID=sa;Password=@tesrt")
    
    'Save it back
    document.Save("Progect.exe.config")

    Friday, August 4, 2017 3:09 PM
  • Something to consider along with changing the value is protecting your password. The following post shows how that is done.

    Not knowing the reason why you are doing this have you considered app.config transformations (native to web projects but doable with window desktop apps) using SlowCheetah. Of course this may fit your needs but wanted to toss it out there. Usually transformations are used for changing environments e.g. from Debug to Release.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, August 4, 2017 5:36 PM
    Moderator
  • Another approach

            Dim xe As XElement
            ' to load from a file
            ' Dim yourpath As String = "your path here"
            'xe = XElement.Load(yourpath)
    
            ' for testing
            xe = <configuration>
                     <configSections>
                     </configSections>
                     <connectionStrings>
                         <add name="Person.My.MySettings.ConnectionString" connectionString="Data Source=192.168.0.1;Initial Catalog=Person;User ID=sa;Password=@hghoh159A"
                             providerName="System.Data.SqlClient"/>
                     </connectionStrings>
                     <system.diagnostics>
                         <sources>
                             <!-- This section defines the logging configuration for My.Application.Log -->
                             <source name="DefaultSource" switchName="DefaultSwitch">
                                 <listeners>
                                     <add name="FileLog"/>
                                     <!-- Uncomment the below section to write to the Application Event Log -->
                                     <!--<add name="EventLog"/>-->
                                 </listeners>
                             </source>
                         </sources>
                         <switches>
                             <add name="DefaultSwitch" value="Information"/>
                         </switches>
                         <sharedListeners>
                             <add name="FileLog"
                                 type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
                                 initializeData="FileLogWriter"/>
                             <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
                             <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
                         </sharedListeners>
                     </system.diagnostics>
                     <startup useLegacyV2RuntimeActivationPolicy="true">
                         <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
                     </startup>
                 </configuration>
    
            Dim cxe As XElement = <add name="Person.My.MySettings.ConnectionString" connectionString="Data Source=192.168.10.1;Initial Catalog=Person;User ID=sa;Password=@tesrt"
                                      providerName="System.Data.SqlClient"/>
    
            xe.<connectionStrings>.<add>.First.ReplaceWith(cxe)
            ' to save file
            ' xe.Save(yourpath)

    This uses Xml.Linq to achieve the result.


    "Those who use Application.DoEvents() have no idea what it does and those who know what it does never use it." - MSDN User JohnWein    Multics - An OS ahead of its time.


    • Edited by dbasnett Saturday, August 5, 2017 12:53 PM
    • Proposed as answer by Frank L. Smith Saturday, August 5, 2017 1:03 PM
    Saturday, August 5, 2017 12:50 PM
  • Hi sh2015,

    Based on your description, you want to modify connection in app.config, please refer to the code below.

      Dim sNewConnStr As String = ""
            Dim xml = XElement.Load("D:\T.xml")
            'Get the first config section (first connection string info)
            Dim connStrXML = xml.Descendants("connectionStrings").Elements().First()
    
            'Get the connection string value
            Dim connStr = connStrXML.Attribute("connectionString").Value
    
            'Create an array with ';'
            Dim arrConn() As String = connStr.Split(";")
    
            For i As Int32 = 0 To arrConn.Length - 1
                'Get the attribute and value splitted by "="
                Dim arrSubConn() As String = arrConn(i).Split("=")
                If (arrSubConn.Length = 2) Then
                    Dim sConnAttr As String = ""
                    Dim sConnValue As String = ""
                    sConnAttr = arrSubConn(0)
                    sConnValue = arrSubConn(1)
    
                    'Change Database name 
                    If (sConnAttr = "Data Source") Then
                        'This is the place where you will be changing the database name 
                        sConnValue = "192.168.10.1"
                    End If
                    If (sConnAttr = "Password") Then
    
                        sConnValue = "@tesrt"
                    End If
    
                    'Generate newly altered connection string
                    sNewConnStr += sConnAttr + "=" + sConnValue + ";"
                End If
            Next
    
            'After doing everything you need To save it back To the same file,
    
            'Modify the existing connection string information
            connStrXML.SetAttributeValue("connectionString", sNewConnStr)
    
            'Saving config at the same place
            xml.Save("D:\T.xml")
            MessageBox.Show("Update successfully!")

    Best Regards,

    Cherry


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by sh 2020 Monday, August 7, 2017 5:40 PM
    Monday, August 7, 2017 7:29 AM
    Moderator