Duplicate elements when adding XElement to XDocument
- by Andy
I'm writing a program in C# that will go through a bunch of config.xml files and update certain elements, or add them if they don't exist. I have the portion down 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'm running into issues when I want to add an element that doesn't exist. Most of the time part of the tree is in place and when I use my code it adds another identical tree, and that causes the program reading the xml to blow up.
here is how I am attempting to do it
xdoc.Element("project").Add(new XElement("logRotator", new XElement("daysToKeep", _day)));
and that results in a structure like this(The numToKeep tag was already there):
<project>
<logRotator>
<daysToKeep>10</daysToKeep>
</logRotator>
<logRotator>
<numToKeep>13</numToKeep>
</logRotator>
</project>
but this is what I want
<project>
<logRotator>
<daysToKeep>10</daysToKeep>
<numToKeep>13</numToKeep>
</logRotator>
</project>