Search code examples
c#.netxmlxsdxelement

how to iterate through intersection of nodes


How can I iterate only through the common nodes between two documents?

Right now, I am able to iterate through all the nodes of my document:

var xmlBody = @"<?xml version="1.0" encoding="UTF-8"?>
<Visit>
   <Person>...</Person>
   <Name>...</Name>
   <Color>...</Color>
</Visit>";
    var xdoc = XDocument.Parse(xmlBody);
    foreach (XElement child in xdoc.Elements())
                {//do stuff}

I'd like to ONLY iterate through the common nodes between xdoc.Elements() and my nodeList:

var nodeList = new List<string> { "Name", "LastName", "Color" };

The intersection of the nodeList and the xdoc would be just these nodes: Name, Color:

How can I iterate against the intersection, something like this

foreach(XElement child in xdoc.Elements().Intersect(nodeList))

Solution

  • I would use Linq Where and Contains like this:

            var xmlBody = @"<?xml version=""1.0"" encoding=""UTF-8""?>
    <Visit>
       <Person>...</Person>
       <Name>...</Name>
       <Color>...</Color>
    </Visit>";
            var xdoc = XDocument.Parse(xmlBody);
            var nodeList = new List<string> { "Name", "LastName", "Color" };
    
            var intersectedElements = xdoc.Elements()
                .First() //<Visit>
                .Elements()
                .Where(element => nodeList.Contains(element.Name.LocalName));
    
            foreach (XElement child in intersectedElements)
            {
                Console.WriteLine($"{child.Name.LocalName}: {child.Value}");
            }
    

    If you want elements that could be nested deeper than use Descendants.

            var intersectedNestedElements = xdoc.Descendants()
                .Where(element => nodeList.Contains(element.Name.LocalName));
    
            foreach (XElement child in intersectedNestedElements)
            {
                Console.WriteLine($"{child.Name.LocalName}: {child.Value}");
            }
    

    Both output:

    Name: ...
    Color: ...