What is the fastest way to combine two xml files into one

后端 未结 11 1544
广开言路
广开言路 2020-11-29 01:43

If I have two string of xml1 and xml2 which both represent xml in the same format. What is the fastest way to combine these together? The format is not important, but I ju

相关标签:
11条回答
  • 2020-11-29 02:10

    Best solution to me, based on Jose Basilio answer, slightly modified,

    var combinedUnique = xml1.Descendants()
        .Union(xml2.Descendants());
    combinedUnique.First().Save(#fullName)
    
    0 讨论(0)
  • 2020-11-29 02:12

    Since you asked for the fastest:

    If (and only if) the xml structure is always consistent: (this is pseudo code)

    string xml1 = //get xml1 somehow
    string xml2 = //get xml2 somehow
    xml1 = replace(xml1, "<?xml version=\"1.0\" encoding=\"utf-8\"?>", "");
    xml1 = replace(xml1, "<allnodes>", "");
    xml1 = replace(xml1, "</allnodes>", "");
    xml2 = replace(xml2, "<allnodes>", "<allnodes>\n" + xml1);
    

    It's a giant hack but it's fast. Expect to see it on TheDailyWTF when your colleagues find it.

    0 讨论(0)
  • 2020-11-29 02:14

    The easiest way to do this is using LINQ to XML. You can use either Union or Concat depending on your needs.

    var xml1 = XDocument.Load("file1.xml");
    var xml2 = XDocument.Load("file2.xml");
    
    //Combine and remove duplicates
    var combinedUnique = xml1.Descendants("AllNodes")
                              .Union(xml2.Descendants("AllNodes"));
    
    //Combine and keep duplicates
    var combinedWithDups = xml1.Descendants("AllNodes")
                               .Concat(xml2.Descendants("AllNodes"));
    
    0 讨论(0)
  • 2020-11-29 02:22

    You have two basic options:

    1. Parse the xml, combine the data structures, serialize back to xml.

    2. If you know the structure, use some basic string manipulation to hack it. For example, in the example above you could take the inside of allnodes in the two xml blocks and put them in a single allnodes block and be done.

    0 讨论(0)
  • 2020-11-29 02:23

    If you can guarantee this format you can combine them by doing string manipulation:

    • Read the first file, keep everything before "</AllNodes>"
    • Read the second file, remove the part up to "<AllNodes>"
    • Combine those strings.

    This should be the fastest way since no parsing is needed.

    const string RelevantTag = "AllNodes";
    
    string xml1 = File.ReadAllText(xmlFile1);
    xml1 = xml1.Substring(0, xml.LastIndexOf("</" + RelevantTag + ">"));
    
    string xml2 = File.ReadAllText(xmlFile2);
    xml2 = xml2.Substring(xml.IndexOf("<" + RelevantTag + ">") + "<" + RelevantTag + ">".Length, xml1.Length);
    
    File.WriteAllText(xmlFileCombined, xm1 + xml2);
    

    That said I would always prefer the safe way to the fast way.

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