I am writing a C # program that will go through a bunch of config.xml files and update some elements or add them if they do not exist. I have a part that updates an element if it exists with this code:
XDocument xdoc = XDocument.Parse(ReadFile(_file));
XElement element = xdoc.Elements("project").Elements("logRotator")
.Elements("daysToKeep").Single();
element.Value = _DoRevert;
But I am having problems when I want to add an item that does not exist. In most cases, part of the tree is in place, and when I use my code, it adds another identical tree, and this makes the program read xml explode.
this is how i try to do it
xdoc.Element("project").Add(new XElement("logRotator", new XElement("daysToKeep", _day)));
and this leads to such a structure (this numToKeep tag already exists):
<project>
<logRotator>
<daysToKeep>10</daysToKeep>
</logRotator>
<logRotator>
<numToKeep>13</numToKeep>
</logRotator>
</project>
but that is what i want
<project>
<logRotator>
<daysToKeep>10</daysToKeep>
<numToKeep>13</numToKeep>
</logRotator>
</project>
source
share