Reputation: 2318
I would like to complete the below XML so all Parent elements have all 3 child elements.
<Parent>
<Child1></Child1>
<Child2></Child2>
<Child3></Child3>
</Parent>
<Parent>
<Child3></Child3>
</Parent>
<Parent>
<Child1></Child1>
<Child3></Child3>
</Parent>
So i got the below code
var elementsToChange = inputDoc.Descendants(CommonConstant.Parent);
foreach (var element in elementsToChange)
{
if (element.Element(CommonConstant.Child1) == null)
{
//add child1 at 1
}
if (element.Element(CommonConstant.Child2) == null)
{
//add child2 at 2
}
}
But i can't find an Insert() or AddAT() on element. (and since i dont know what childs exist, using add afetr or before self are hard to use.)
Is there a way of adding a child at a certain location?
Upvotes: 0
Views: 244
Reputation: 2135
XmlElement has two methods to add a chile: Append and Prepend, adding to the end of beginning of the children list. You cannot add to the middle.
If you really want that, you can remove all children (RemoveAll, but that will also remove attributes, which you do not have in this example) and then add in the order you want (AppendChild).
Upvotes: 2
Reputation: 1769
Try this:
foreach (var element in elementsToChange)
{
XElement lastChild = null;
foreach(var childName in Enumerable.Range(1, 3).Select(x => "Child" + x))
{
var child = element.Element(childName);
if(child == null)
{
child = new XElement(childName);
if(lastChild == null)
element.AddFirst(child);
else
{
lastChild.AddAfterSelf(child);
}
}
lastChild = child;
}
}
Upvotes: 1