Reputation: 315
I'm just creating an app that stores the settings in a xml file. If I now want to save a new parameter, I need to check if that parameter already exists and update it or add it to the document.
Actually I solve it this way:
XDocument xDocument = XDocument.Load(appDataFolder + @"\settings.xml");
foreach(XElement xElement in xDocument.Descendants("Settings"))
{
if(xElement.Element("projectFile") != null)
xElement.Element("projectFile").Value = projectFile;
else
xElement.Add(new XElement("projectFolder", projectFile));
if (xElement.Element("projectFolder") != null)
xElement.Element("projectFolder").Value = projectFolder;
else
xElement.Add(new XElement("projectFolder", Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments)));
}
xDocument.Save(appDataFolder + @"\settings.xml");
This is the actual settings.xml:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--System-Settings-->
<Settings version="1.0.0.0">
<projectFile>C:\Users\Public\Documents\project.prj</projectFile>
<projectFolder>C:\Users\Public\Documents</projectFolder>
</Settings>
Isn't there a more handy way that automatically adds an element, if it doesn't exist?
Upvotes: 0
Views: 141
Reputation: 31873
System.Xml.Linq.XElement
actually has a method that does exactly that, namely SetElementValue
.
It takes an XName
and the desired content, adding or updating according to your intuition.
Both
var xml = XElement.Parse("<outer></outer>");
xml.SetElementValue("inner", 2);
and
var xml = XElement.Parse("<outer><inner>1</inner></outer>");
xml.SetElementValue("inner", 2);
result in
<outer><inner>2</inner></outer>
As we can see from the remarks section, it was designed with your use case in mind.
This method is designed to make it easy to maintain a list of name/value pairs as a set of children elements. When maintaining the list, you need to add pairs, modify pairs, or delete pairs. If you call this method passing a name that does not exist as a child element, this method creates a child element for you. If you call this method passing the name of an existing child element, this method modifies the value of the child element to the value that you specify. If you pass null for value, this method removes the child element.
Upvotes: 1