Home > Mobile >  Find Missing Element in XML c#
Find Missing Element in XML c#

Time:08-13

Is there any way to find the missing element from XML2.xml with XML1.xml

Example XML1

<Student ID="1" Name="John"/>
<Student ID="2" Name="Antony"/>
<Student ID="3" Name="Chris"/>

XML2

<Student ID="1" Name="John"/>
<Student ID="3" Name="Chris"/>

OUTPUT

Student ID = "2" Name="Antony" is missing something like other..

Actually I was comparing two XML Files but it shows the Difference but it always ignores the missing one or the new one which need to update on client xml.

Hope this info will help :)

CodePudding user response:

Assuming you have these two documents:

<document>
  <Student ID="1" Name="John"/>
  <Student ID="2" Name="Antony"/>
  <Student ID="3" Name="Chris"/>
</document>

AND

<document>
  <Student ID="1" Name="John"/>
  <Student ID="3" Name="Chris"/>
</document>

You can use something like this:

public static void ReadXml()
{
    var doc1Students = GetStudents(XDocument.Load("your/path1")).ToList();
    var doc2Students = GetStudents(XDocument.Load("your/path2")).ToHashSet();
    foreach (var (id, name) in doc1Students)
    {
        if (!doc2Students.Contains((id, name)))
        {
            Console.WriteLine($"Student ID = \"{id}\" Name=\"{name}\" is missing");
        }
    }
}

private static IEnumerable<(string Id, string Name)> GetStudents(XContainer doc)
{
    return doc.Descendants("Student")
        .Select(n => (n.Attribute("ID")?.Value, n.Attribute("Name")?.Value))
        .Where(tuple => !string.IsNullOrEmpty(tuple.Item1));
}
  • Related