簡體   English   中英

如何將XML塊從一個文檔復制到另一個文檔?

[英]How can I copy a block of XML from one document to the other?

我有兩個dataGridViews分別加載一個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塊?

非常感謝你的幫助!

假設您要將元素塊從text1.xml復制到text2.xml,可以使用LINQ to XML,下面的示例假定將所有條目從text1復制到text 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插入到最后Last ,但是如果您擔心訂購,可以在xDoc2上使用LINQ查找正確的位置,然后進行插入。

每個XmlNode都有幾種方法(而XmlDocument是XmlNode的子類),因此您可以使用xDoc.SelectNodes()xDoc.SelectSingleNode()來選擇文檔結構中任何位置的特定節點,然后將該節點存儲在對象中(讓我們稱它為needleNode),然后執行xDoc.InsertBefore(Copy,ref needleNode)xDoc.InsertAfter(Copy,refneedleNode) 使用這四個函數,您可以將xml部分插入到第二個xml結構的絕對任何部分。

如果控件是數據綁定的,則無需在DataGridView的rows集合中添加/刪除行(實際上,您不能這樣做)。 而是將它們添加到基礎數據源集合(您要在其中設置該集合的DataGridView的DataSource屬性)。 之后,您將需要刷新兩個datagridviews的視圖以反映更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM