[Solved] C# Add nodes in xml


This projects both sets into an anonymous object List, makes comparisons, and gives you a set of anonymous objects that don’t yet exist by which you can add to the out XML.

public static List<object> GetInStudents(XDocument sourceXmlDoc)
{
    IEnumerable<XElement> inStudentsElements = 
    sourceXmlDoc.Root.Elements("Classes").Descendants("Class")
                     .Descendants("Students").Descendants("Student");

    return inStudentsElements.Select(i => 
        new { Id = i.Elements().First().Value, 
            Name = i.Elements().Last().Value }).Cast<object>().ToList();
}

public static List<object> GetOutStudents(XmlDocument targetXmlDoc)
{
    XmlNodeList outStudentsElements = targetXmlDoc.GetElementsByTagName("Students")[0].ChildNodes;

    var outStudentsList = new List<object>();

    for (int i = 0; i < outStudentsElements.Count; i++)
    {
        outStudentsList.Add(new { Id = outStudentsElements[i].ChildNodes[0].InnerText, 
                                  Name = outStudentsElements[i].ChildNodes[1].InnerText });
    }

    return outStudentsList;
}

And you compare them as such:

var inStudents = GetInStudents(sourceXmlDoc);
var outStudents = GetOutStudents(targetXmlDoc);

if (inStudents.SequenceEqual(outStudents))
{
    return;
}
else
{
    var elementsToAdd = inStudents.Except(outStudents);

    foreach (var element in elementsToAdd)
    {
        // create xmlNode with element properties, add element to xml
    }
}

3

solved C# Add nodes in xml