I would like to clone a Xml element, insert it to the end of the element list and save the document. Could someone explain how it is done in linq to xml
<Folders>
<Folder ID="1" Name="Music" PathValue="Root/Music" ParentId="0"></Folder>
<Folder ID="2" Name="Rock" PathValue="Root/Rock" ParentId="1"></Folder>
</Folders>
think of the xml element Folder as Virtual folder on disk. I would like to copy the folder Rock into music hence the resulting xml should become as below
<Folders>
<Folder ID="1" Name="Music" PathValue="Root/Music" ParentId="0"></Folder>
<Folder ID="2" Name="Rock" PathValue="Root/Rock" ParentId="0"></Folder>
<Folder ID="3" Name="Rock" PathValue="Root/Music/Rock" ParentId="1"></Folder>
</Folders>
var source = new XElement((from folder in _xmlDataSource.Descendants("Folders").Descendants("Folder") where
wallet.Attribute("ID").Value.Equals(sourceWalletId, StringComparison.OrdinalIgnoreCase) select wallet).First());
//source is a clone not the reference to node.
var directChildren = (from folder in _xmlDataSource.Descendants("Folders").Descendants("Folder") where folder.Attribute("PathValue").Value.Contains(sourcePathValue) select folder);
//How do i clone this
Could someone help me with #2 and #4?
You know about the constructor that takes another XElement to create a copy of it, have you tried this?
var copiedChildren = from folder in _xmlDataSource.Descendants("Folders").Descendants("Folder")
where folder.Attribute("PathValue").Value.Contains(sourcePathValue)
select new XElement(folder);
as you have already cloned source
, you can insert those into that node (assuming they should be children of the copied node)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With