¿Cómo clono un elemento xml usando Linq to Xml?
Frecuentes
Visto 6,889 veces
4
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
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>
Contexto
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
Resultado requerido
<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 to be carried out
- Clone the source node ( Done #1)
- Clone the other nodes inside source node ( Don't know how to do it #2)
- Generate new ID for the nodes inside #2 and change pathvalue ( I know how to do this)
- Insertar el nodo #1 y nodos 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
Pregunta
Could someone help me with #2 and #4?
2 Respuestas
7
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)
contestado el 22 de mayo de 12 a las 08:05
3
If you're only concerned with copying elements nested inside the source element, you could 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);
contestado el 22 de mayo de 12 a las 08:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas xml linq linq-to-xml xelement or haz tu propia pregunta.