How to clone an xml element using Linq in Xml

I would like to clone an Xml element, insert it at the end of the list of elements, and save the document. Can someone explain how this is done in linq for xml

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> 

Context

think of the xml Folder element as a virtual folder on disk. I would like to copy the Rock folder to music, so the resulting xml should be lower

Desired Result

  <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> 

Operations in progress

  • Clone source node (Done # 1)
  • Clone other nodes inside the node source (don't know how to do this # 2)
  • Create a new identifier for the nodes inside # 2 and change the path value (I know how to do this)
  • Insert node # 1 and nodes from # 2 (don't know)

1

 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. 

2

 var directChildren = (from folder in _xmlDataSource.Descendants("Folders").Descendants("Folder") where folder.Attribute("PathValue").Value.Contains(sourcePathValue) select folder); //How do i clone this 

Question

Can someone help me with C # 2 and # 4?

+4
source share
2 answers

You know about a constructor that accepts 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 cloned source , you can paste them into this node (if they should be children of the copied node)

+7
source

If you are only interested in copying elements nested in the original element, you can use this:

 XDocument xdoc = new XDocument("filename"); XElement source = xdoc.Root.Elements("Folder").Where(f => f.Attribute("ID") == "1").First(); XElement target = new XElement(source); target.Add(new XAttribute("ParentId", source.Attribute("ID")); // TODO update ID and PathValue of target xdoc.Root.Add(target); 
+3
source

Source: https://habr.com/ru/post/1413683/


All Articles