Search code examples
c#xmlinsertafter

Unable to use InsertAfter for XmlDocument in c#


Hi below are the XML files which is master XML

<?xml version="1.0" encoding="utf-16"?>
 <Verify>
  <ver>
     <ECU>
      <values>
      </values>
     </ECU>
  </ver>
 </Verify>

I have multiple files which are of same structure as below

<?xml version="1.0" encoding="utf-16"?>
 <Verify>
  <ver>
     <ECU>
      <values>
      </values>
     </ECU>
  </ver>
 </Verify>

I want my output as

<?xml version="1.0" encoding="utf-16"?>
 <Verify>
  <ver>
     <ECU>
      <values>
      </values>
     </ECU>

     <ECU>
      <values>
      </values>
     </ECU>

     <ECU>
      <values>
      </values>
     </ECU>
  </ver>
 </Verify>

I am using below code to read first one as master xml and other files from xmls folder. I want to add ECU node from these files under ECU node of master file.

XmlDocument xmlMaster = new XmlDocument();
        xmlMaster.Load(@"C:\MasterXMLFile.xml");
        XmlElement masterRoot = xmlMaster.DocumentElement;
        XmlNode masterParent = masterRoot.LastChild.LastChild;
        var downloadfolder = @"C:\AllXMLs\xmls\";
        string[] files = Directory.GetFiles(downloadfolder);
        foreach (var xx in files)
        {
            XmlNode masterNode = masterRoot.LastChild.LastChild;
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xx);
            XmlElement root = xdoc.DocumentElement;
            XmlElement tempNode = (XmlElement)root.LastChild.LastChild;
            masterRoot.InsertAfter(tempNode, masterRoot.SelectSingleNode("//ECU").ParentNode);
        }
        xmlMaster.Save(@"C:\mergeg.xml");

I am getting error at InsertAfter statement as Object reference not set to an instance of an object.

Please suggest me any solution.


Solution

  • Your tempNode is from xdoc document context. You should import it to xmlMaster document context:

    XmlNode importedECU = xmlMaster.ImportNode(tempNode, true);
    

    Also instead of InsertAfter it's better to use AppendChild and append new ECU nodes as children of master ver element:

    var masterVer = masterRoot.SelectSingleNode("//ver");
    
    foreach(var file in files)
    {
       var xdoc = new XmlDocument();
       xdoc.Load(file);
       var tempNode = xdoc.DocumentElement.LastChild.LastChild;
       var importedECU = xmlMaster.ImportNode(tempNode, true); 
       masterVer.AppendChild(importedECU);
    }