将元素从一个 xml 文件移动到另一个 xml 文件
本文关键字:文件 xml 移动 另一个 一个 元素 | 更新日期: 2023-09-27 18:35:37
I 有两个 XML 文件,其中包含以下元素(仅限项目元素及其子元素):
<warehouse>
<cat id="computer">
<item>
<SN>value</SN>
<name>value</name>
<quantity>value</quantity>
<description>value </description>
<price>value</price>
</item>
</cat>
<cat id="Stationery">
<item>
<SN>value</SN>
<name>value</name>
<quantity>value</quantity>
<description>value </description>
<price>value</price>
</item>
</cat>
</warehouse>
我这里有以下代码,它删除了这些元素(仅限项目元素及其子元素)。
xmlDoc.Root.Descendants("cat").Where(x => x.Attribute("id").Value == "computer")
.Descendants("item").Where(x => x.Element("SN").Value.Trim() == Dropdownlist.Text)
.Remove();
xmlDoc.Save(@"YourXML.xml");
我想要的是将这些元素从第一个 XML 文件复制到第二个 XML 文件,然后再删除它们。如何使用 LINQ 执行此类过程?
您可以先轻松存储查询结果,将副本添加到其他XDocument
实例,然后调用Remove
:
var itemsToRemove = xmlDoc.Root.Descendants("cat")
.Where(x => x.Attribute("id").Value == "computer")
.Descendants("item")
.Where(x => x.Element("SN").Value.Trim() == Dropdownlist.Text)
.ToList();
// Add is smart enough to perform deep clone of your XML structure on add
otherDoc.Root.Element("cat").Add(itemsToRemove);
itemsToRemove.Remove();
xmlDoc.Save(@"YourXML.xml");