Having a little bit of an issue with using XElement/LINQ to add a new element, when the path is unknown, and am fairly new to LINQ as well. In C#, Winforms
Edit: The 'ID' values in the xml are actually GUID's, just trimmed down here for ease of reading.
For example, if I have the below xml file:
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Structure>
<Nodes>
<Node ID="1" Name="A" />
<Node ID="2" Name="B" />
<Node ID="3" Name="C" >
<Nodes>
<Node ID="4" Name="D" />
<Node ID="5" Name="E" >
<Nodes>
<Node ID="6" Name="F" />
</Nodes>
</Node>
</Nodes>
</Node>
</Nodes>
</Structure>
</Root>
Then my code snippet for inserting a new node (ID = 7 Name = G) underneath Node 2 / B is: (Note: I am previously identifying the target, in this case 2, hardcoded for brevity)
// Add Node:
_XML_Modify.Element("Structure")
.Elements("Nodes")
.Elements("Node")
.Where(item => item.Attribute("ID").Value == 2).FirstOrDefault()
.AddAfterSelf(new XElement("Node",
new XAttribute("ID", 7),
new XAttribute("Name", "G")
));
But how can I add a new node, if I am not sure of the target? If for example to add the new node underneath node 4/D or 6/F where the path is different then the above.
Is it best to use recursion to find my target node in this scenario? I've tried that and struggled a little bit, but am thinking of doing a "Find", then if it has child nodes, call recursively until the target node is found.
IDproperty have unique values?