我想克隆一个Xml元素,将其插入元素列表的末尾并保存文档。有人可以解释如何在linq中完成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>
将xml元素Folder视为磁盘上的Virtual文件夹。我想将文件夹Rock复制到音乐中,因此生成的xml应该如下所示
<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
有人可以帮助我#2和#4吗?
答案 0 :(得分:7)
你知道构造函数需要另一个XElement来创建它的副本吗,你试过这个吗?
var copiedChildren = from folder in _xmlDataSource.Descendants("Folders").Descendants("Folder")
where folder.Attribute("PathValue").Value.Contains(sourcePathValue)
select new XElement(folder);
因为你已经克隆了source
,你可以将它们插入到那个节点中(假设它们应该是复制节点的子节点)
答案 1 :(得分:3)
如果您只关心嵌套在source元素中的复制元素,可以使用:
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);