Tayfur Yılmaz
Tayfur Yılmaz

Reputation: 21

Set element attribute value in XML with Linq

I have the following XML:

<appsettings>

    <add key="MDXQueryDirectory" value="" />

    <add key="URLPrefix" value="/Manager" />

</appsettings>

and code:

 XElement doc = XElement.Load(@"config_path");


 var element = doc.Elements("add")
            .SingleOrDefault(x => x.Attribute("key").Value == "MDXQueryDirectory");


 element.SetAttributeValue("value", txtMDXQueryDirectory.Text);

I want to assign the txtMDXQueryDirectory textbox data to the MDXQueryDirectory appSsetting. First I use Single method but it doesn't work and I researched on google I found this page so bugs solve related that article. But know SingleOrDefault method doesn't work. It throws NullPointerException (Object reference not set to an instance an object)

How can I solve problem or maybe you suggest different idiom to set value data in xml?

Upvotes: 0

Views: 3303

Answers (2)

Tayfur Yılmaz
Tayfur Yılmaz

Reputation: 21

 string config_file = @"config_file_path";

 var element = doc.Element("appSettings").Elements("add")
                           .SingleOrDefault(x => x.Attribute("key").Value.ToString() == "MDXQueryDirectory");

 element.SetAttributeValue("value", txtMDXQueryDirectory.Text);
 doc.Save(@"config_file_path");

This code block work fine. I think the problem was related xml nodes in my side. Thanks for all replies.

Upvotes: 0

DGibbs
DGibbs

Reputation: 14618

You need to change the query where you're selecting the element to update, it should be:

 XDocument doc = XDocument.Load(@"config_path");

 var element = doc.Descendants().Elements("add")
               .SingleOrDefault(x => x.Attribute("key").Value == "MDXQueryDirectory");

 element.SetAttributeValue("value", txtMDXQueryDirectory.Text);

 doc.Save(@"config_path");

You should also be using XDocument rather than XElement when getting the file.

Note: XDocument.Load(@"config_path") - should point to the location of your XML file. Currently it does not.

Upvotes: 3

Related Questions