1

I have a problem with adding an element to an XML file using C#. I have my App.config files somewhere in my diff directory. So I am using LINQ to retrieve the values I want and to set the value from TextBoxes.

<appSettings>
    <add key="Something" value="false" />
    <add key="UserName" value="user0001" />
    <add key="Password" value="123456" />
    <add key="Environment" value="" />
    <add key="DBUserName" value="DBname23" />
    <add key="DBPassword" value="12345678" />
</appSettings>

The above is my XML file. I am able to retrieve the values of UserName and Password and set it with the encrypted ones. The way I am doing is shown below:

var doc1 = XDocument.Load(appConfigFile1);

var list1 = from appNode in doc1.Descendants("appSettings").Elements()
            where appNode.Attribute("key").Value == "UserName"
            select appNode;
var list2 = from appNode in doc1.Descendants("appSettings").Elements()
            where appNode.Attribute("key").Value == "Password"
            select appNode;
var list3 = from appNode in doc1.Descendants("appSettings").Elements()
            where appNode.Attribute("key").Value == "DBUserName"
            select appNode;
var list4 = from appNode in doc1.Descendants("appSettings").Elements()
            where appNode.Attribute("key").Value == "DBPassword"
            select appNode;
var element1 = list1.FirstOrDefault();
var element2 = list2.FirstOrDefault();
var element3 = list3.FirstOrDefault();
var element4 = list4.FirstOrDefault();
element1.Attribute("value").SetValue(txtbox1);
element2.Attribute("value").SetValue(txtbox2);
element3.Attribute("value").SetValue(txtbox3);
element4.Attribute("value").SetValue(txtbox4);
doc1.Save(appConfigFile1);

The requirements are such that if one of the elements from the XML file is deleted, I should be able to create a same element with key and value.

Example: Please compare the above xml with the below:

<appSettings>
    <add key="HasUI" value="false" />
    <add key="Password" value="123456" />
    <add key="Environment" value="" />
    <add key="DBUserName" value="DBname23" />
    <add key="DBPassword" value="12345678" />
</appSettings>

Above the element Username is missing. So how can I create an XML element like <add key="UserName" value="" /> and set that to that same place in XML file?

The error I am getting when I load the XML file in C# is NullReferenceException.

Please help me.

3
  • Why does it have to be in order? I just XML poke on mine (I actually do mine with powershell for this) Commented Jul 24, 2012 at 21:16
  • do you want to change the app.config or just put a default value when you don't have a value in app.config? Commented Jul 24, 2012 at 21:18
  • @jcolebrand hey!! i dont need that to be in order..i have edited the question Commented Jul 24, 2012 at 21:20

3 Answers 3

3

For goodness sake, anything you do more than once should be a function!

function UpdateOrCreateAppSetting(XMLDocument doc, string key, string value)
{
    var list = from appNode in doc.Descendants("appSettings").Elements()
            where appNode.Attribute("key").Value == key
            select appNode;
    var e = list.FirstOrDefault();

    // If the element doesn't exist, create it
    if (e == null) {
        e = doc.CreateElement("add")
        e.Attributes.Append("key", key);
        e.Attributes.Append("value", value);
        doc.Descendants("appSettings").AppendChild(e);

    // If the element exists, just change its value
    } else {
        e.Attribute("value").SetValue(value);
    }
}

Now call the function four times and you're good. ;)

Sign up to request clarification or add additional context in comments.

3 Comments

Fixed a typo in the function.
@TedSpence What if I want to use Xdocument?
Per msdn.microsoft.com/en-US/library/…, the XmlAttributeCollection.Append method takes one parameter, a node of type XmlAttribute. But you're passing two strings. How? I don't see that as an override. Is that a different method?
1

if you just want to put a default value when the app.config is not as you expect you can do something like that:

var doc1 = XDocument.Load(appConfigFile1);

                var list1 = from appNode in doc1.Descendants("appSettings").Elements()
                            where appNode.Attribute("key").Value == "UserName"
                            select appNode;
                var list2 = from appNode in doc1.Descendants("appSettings").Elements()
                            where appNode.Attribute("key").Value == "Password"
                            select appNode;
                var list3 = from appNode in doc1.Descendants("appSettings").Elements()
                            where appNode.Attribute("key").Value == "DBUserName"
                            select appNode;
                var list4 = from appNode in doc1.Descendants("appSettings").Elements()
                            where appNode.Attribute("key").Value == "DBPassword"
                            select appNode;
                // the values of missing elements are null so you can use the "??" operator                                               //hat put something else when you have null
                var element1 = list1.FirstOrDefault() ?? "your default value";
                var element2 = list2.FirstOrDefault() ?? "your default value";
                var element3 = list3.FirstOrDefault() ?? "your default value";
                var element4 = list4.FirstOrDefault() ?? "your default value";
                element1.Attribute("value").SetValue(txtbox1);
                element2.Attribute("value").SetValue(txtbox2);
                element3.Attribute("value").SetValue(txtbox3);
                element4.Attribute("value").SetValue(txtbox4);
                doc1.Save(appConfigFile1);

1 Comment

Sorry Buddy!! I want to change the appconfig.Not just put the defualt... My bad.... i am getting a Null reference Exception near element1.Attribute("value").SetValue(txtbox1);
0

The NullReference is coming at the

element1.Attribute("value").SetValue(txtbox1);

statement, is it not? The FirstOrDefault above has left element1 to be null. I think you want to test for null before accessing the Attribute property; failing that test, you can then supply your default.

1 Comment

Yes...Absolutly thats what happening.... yes i am dng that... but i am checking that null in element1..in that condition i want to write a c# script which can add <add key="UserName" value="" /> attribute to that AppSettings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.