Search code examples
c#xmlxelement

C# Find XElement Descendant based on multiple attributes


I have to add information to an existing XML file. The data is going to be underneath an existing node. This has to do with Patient data, and I have to find the existing patient within the XML, so I can add the subsequent data to it. This data is encapsulated within a "PATIENTDETAILS" element.

While I found many articles on how to find a descendant via a single attribute, I need to use multiple attributes can try as I might, I can't seem to find how to use multiple attributes.

This is my current query (C#):

XElement patient = xmlDoc.Descendants(ns + "_PATIENTDETAILS").ToList().WHERE
(x => (string)x.Element(ns + "_PatientName") == currentPatientName).FirstOrDefault();

I need to add "_PatientAccNo", "_HicNo" and "_MedRecNo" to the where clause to ensure I find the right _PATIENTDETAILS before adding a new element beneath that patient with the new data.

I'm adding the new element after this query by doing:

XElement serviceLines = patient.Element("_PATIENTDETAILS");

xmlDoc.Element("_OCROUTPUT).Element("_PATIENTDETAILS").Add(new XELEMENT("_SERVICELINES",
new XElement(name, data),
Blah blah blah

If someone can give me an example of using multiple where clauses in finding a Descendant, I'd appreciate it.


Solution

  • You can combine conditions with a logical and which is && in C#.

    XElement patient = xmlDoc.Descendants(ns + "_PATIENTDETAILS")
        .Where(x => (string)x.Element(ns + "_PatientName") == currentPatientName &&
                    (string)x.Element(ns + "another element") == anotherValue &&
                    (string)x.Element(ns + "yet another element") == yetAnotherValue)
        .FirstOrDefault();
    

    See also: Conditional logical AND operator &&.

    And also the .ToList() in there can be dropped. It adds no value.