XElement - Find Node with Two Different Child Values

42 Views Asked by At

Using this list below:

<People>
    <Continent>Asia</Continent>
    <TimeZone>Hong Kong Standard Time</TimeZone>
    <Person>
        <FirstName>Joe</FirstName>
        <LastName>Stevenson</LastName>
    </Person>
    <Person>
        <FirstName>Joe</FirstName>
        <LastName>Hancock</LastName>
    </Person>
    <Person>
        <FirstName>Kirby</FirstName>
        <LastName>Stevenson</LastName>
    </Person>
</People>

I would like to use some XElement LINQ to select the node that contains the FirstName and LastName of Joe Stevenson. I've tried the following code here:

string trimmedFirstName = "Joe";
string trimmedLastName = "Stevenson";
List<XElement> peopleChildren = convertedPayload.Descendants("Person").Where(a => a.Value.Contains(trimmedFirstName)
                && a.Value.Contains(trimmedLastName)).ToList();

But when I use the above code, I believe I return nothing since I'm trying to check a single value. I want to select by the value, being XElement name agnostic (so I should be able to check, for example, if someone has a last name of "Joe" and first name of "Stevenson" so that I can correct that to the actual first and last name of my originating data).

When I use an OR operator in the above LINQ, of course I return too many elements.

Can anyone here give suggestions?

1

There are 1 best solutions below

0
Sekhar On

You can use the Element method to narrow down on the element name. The following should work.

        string trimmedFirstName = "Joe";
        string trimmedLastName = "Stevenson";
        List<XElement> peopleChildren = convertedPayload.Descendants("Person")
            .Where(a => a.Element("FirstName").Value.Contains(trimmedFirstName)
                        && a.Element("LastName").Value.Contains(trimmedLastName)).ToList();