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

前端 未结 3 1243
耶瑟儿~
耶瑟儿~ 2021-01-16 04:54

I have two dataGridViews that load up an XML file each, I have made it so that you can drag and drop rows in between each of the grids. However at the moment, all that it do

相关标签:
3条回答
  • 2021-01-16 05:08

    Assume you want to copy block of elements from text1.xml to text2.xml, you can use LINQ to XML, example below assumes copying all entries from text1 to 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");
    

    But you also can use Where method to filter to get part of xml, sample below is to filter using list of indices:

      var filterIndices = new[] {600, 601, 700, 705};
    
      var doc1Entries =
          xDoc1.Descendants("stentry")
               .Where(x =>         
                   filterIndices.Contains(int.Parse(x.Element("index").Value)));
    

    In here, I assume to insert to the last using Last, but if you care about ordering, you can use LINQ on xDoc2 to find correct position, then do insert.

    0 讨论(0)
  • 2021-01-16 05:12

    If your control is databound, you don't need to add/remove rows to the DataGridView's rows collection (you actually can't do this). Instead, add them to the underlying datasource collection (the collection you are setting in to the DataSource property of the DataGridView). Afterwards you'll need to refresh the view of both datagridviews to reflect the change.

    0 讨论(0)
  • 2021-01-16 05:15

    Every XmlNode has several methods (and XmlDocument is a child class of XmlNode), so you can use xDoc.SelectNodes() or xDoc.SelectSingleNode() to pick a specific node wherever in the document structure, store that node in an object (let's call it needleNode), and then do xDoc.InsertBefore(Copy, ref needleNode) or xDoc.InsertAfter(Copy, ref needleNode). Using these four functions you can insert the xml section to absolutely ANY part in the structure of the second xml.

    0 讨论(0)
提交回复
热议问题