Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 248
  • Last Modified:

LINQ to XML to update an attribue value?

I have this section in an xml file. I need to change the value for the AdminPassword.
What are the LINQ to XML statements I should use?



<configuration>
  <appSettings>
    <add key="AdminUsername" value="admin"/>
    <add key="AdminPassword" value="admin"/>
...
</appSettings>

Open in new window

0
jentel2
Asked:
jentel2
1 Solution
 
Fernando SotoCommented:
Hi jentel2;

Here is code snippet to show how to load the XML file and modify the AdminPassword value and save the results back to the file.

Fernando

using System.Xml.Linq;
 
namespace WindowsFormsApplication52
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            // File location of XML file
            String filename = "web.config";
            // Load the document into the XElement
            XElement webConfig = XElement.Load(filename, LoadOptions.PreserveWhitespace);
            // Find the key AdminPassword and change its password in the value field
            (from ele in webConfig.Element("appSettings").Elements("add")
                where ele.Attribute("key").Value == "AdminPassword"
                select ele).First().SetAttributeValue("value", textBox1.Text);
 
            // Save the XML file back to the system
            webConfig.Save(filename);
            Console.WriteLine("Hello");
        }
    }
}

Open in new window

0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

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