我有两个 dataGridView,每个加载一个 XML 文件,我已经这样做了,以便您可以在每个网格之间拖放行。但是目前,它所做的只是从 dataGridView 复制数据。这工作正常,但我需要复制与该行相关的所有 XML。
这是我必须使用的 XML:
<WindowBuilderProject>
<stringtable>
<stentry>0..607</stentry> //All of the other records
<stentry>
<index>608</index>
<sid>MNUB_AUTO</sid>
<val>
<en>AUTO</en>
</val>
<params>
<fontref>0</fontref>
<numref>0</numref>
<clip>FALSE</clip>
<include>TRUE</include>
<protected>FALSE</protected>
<cwidth>-1</cwidth>
<dwidth>0</dwidth>
</params>
</stentry>
</stringtable>
</WindowBuilderProject>
所以我需要复制用户选择的行的 XML 并将其插入到另一个(相同格式)XML 文档中。
到目前为止我有这个:
string location = "/WindowBuilderProject/stringtable/stentry[index='" + rowIndexOfItemUnderMouseToDrop + "']";
XmlNode Copy = xDoc.ImportNode(xDoc2.SelectSingleNode(location), false);
xDoc.DocumentElement.AppendChild(Copy); //This is just supposed to add it to the end, I will worry about ordering once it works
它运行良好,但所有发生的事情都是我将一个添加到 XML 文件的底部。如何选择整个 XML block ?
非常感谢您的帮助!
最佳答案
假设您想将元素 block 从 text1.xml 复制到 text2.xml,您可以使用 LINQ to XML,下面的示例假设将所有条目从 text1 复制到文本 2:
var xDoc1 = XDocument.Load("C:\\text1.xml");
var xDoc2 = XDocument.Load("C:\\text2.xml");
var doc1Entries = xDoc1.Descendants("stentry");
var cloneEntries = doc1Entries.Select(x => new XElement(x));
xDoc2.Descendants("stentry").Last().AddAfterSelf(cloneEntries);
xDoc2.Save("C:\\text2.xml");
但是你也可以使用Where
方法来过滤获取部分xml,下面的示例是使用索引列表进行过滤:
var filterIndices = new[] {600, 601, 700, 705};
var doc1Entries =
xDoc1.Descendants("stentry")
.Where(x =>
filterIndices.Contains(int.Parse(x.Element("index").Value)));
在这里,我假设使用 Last
插入到最后,但如果您关心顺序,您可以在 xDoc2 上使用 LINQ 找到正确的位置,然后执行插入。
关于c# - 如何将 XML block 从一个文档复制到另一个文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12641206/