My XML Document is as below -
<?xml version="1.0" encoding="utf-8"?>
<Parents>
<Parent id="A" description="A is a parent">
<Children>
<ChildName name = "Son1ofA" />
<ChildName name = "Son2ofA" />
</Children>
</Parent>
</Parents>
Requirement -
- To identify the Element "Parent", clone it. Change the attribute id to "B". Add it as a sibling to itself (making it a new child of "Parents").
The output file is as below -
<Parents> <Parent id="A" description="A is a parent"> <Children> <ChildName name = "Son" /> <ChildName name = "Daughter" /> </Children> </Parent> <Parent id="B" description="A is a parent"> <Children> <ChildName name = "Son" /> <ChildName name = "Daughter" /> </Children> </Parent>
My Code
XDocument myXMLDocument = XDocument.Load("File.xml");
XElement myParentsElement = myXMLDocument.Element("Parents");
XElement myFirstParentElement = myParentsElement.Element("Parent");
XElement myNewParentElement = new XElement(myFirstParentElement);
XAttribute myParentId = myNewParentElement.Attribute("id");
myParentId.Value = "B";
myFirstParentElement.AddAfterSelf(myNewParentElement);
myXMLDocument.Save("NewFile.xml");
And it works perfectly fine, without any issues. Clearly, this is no good programming. Because, I am extracting the Element Parents, then using that as a root node, I am extracting Parent etc.,
What I would want to be able to do is something like this - Directly key in the path - as in /Parents/Parent(XPath), extract that particular Node, make a copy of it, make modifications to its attributes, add it as a sibling and save the Document.
Am I doing something silly?