Merging two xml files in C# without appending and without deleting anything (example given)

后端 未结 3 573
野的像风
野的像风 2021-01-23 07:55

So say I have one xml file such as this:


    shape1

And another xml file like this:

相关标签:
3条回答
  • 2021-01-23 08:15

    I don't think there is an easy solution. Considering that you are not restricted to merging the contents of the Shapes node, i think you will have to parse through the nodes of one of the document recursively, checking whether each of these nodes is present in the other document through XPath. And once you find a node that is common in both the documents, you can merge the contents of one in the other. It is hardly efficient and there may be a better way but thats the best I can think of.

    0 讨论(0)
  • 2021-01-23 08:19

    You can load both files into two XElement objects, locate the target nodes in both objects and add or remove as you wish.

    Here is a sample:

    var doc1 = XDocument.Parse(file1).Element("shapes");
    var doc2 = XDocument.Parse(file2).Element("parentNode").Element("shapes");
    
    doc2.Add(doc1.Nodes());
    
    0 讨论(0)
  • 2021-01-23 08:23

    Psuedo code, I am guessing at the method names.

    ...
    xmlreader xmlToMerge1 = xmlreader.create(XmlSourceVariableHere);
    xmlreader xmlToMerge2 = xmlreader.create(XmlSourceVariableToMergeHere);
    xmlwriter xmlout = new xmlwriter(someStreamOrOther);
    
    xmlout.writeBeginElement("parentnode");
    xmlout.writeBeginElement("shapes");
    
    while (xmlToMerge1.Read())
     {
     if (xmlreader.nodetype == element && xml.Name == "shape")
      {
      xmlToMerge1.WriteNodeTo(xmlout);
      }
     }
    
    while (xmlToMerge2.Read())
     {
     if (xmlToMerge2.nodetype == element && xmlToMerge2.Name == "shape")
      {
      xmlToMerge2.WriteNodeTo(xmlout);
      }
     }
    
    
    xmlout.writeEndNode(); // end shapes
    xmlout.writeEndNode(); // end parentnode
    

    I remember that there is a command to write a node from a reader to a writer, but I don't remember what it is specifically, you'll have to look that one up.

    What exactly do you mean by the following?

    In terms of the merge it basically needs to stick the right leaf nodes in the right places if that makes sense? Without overwriting anything unless the config file has been explicitly written to do so, e.g. a custom "shape 2".

    You'll have to explain your requirements a bit more if you want an answer to be more detailed than simply merging nodes.

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