0

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.

1 Answers1

1

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.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • Thank you, I was trying that (using &&), but I see where I made my syntax error, I appreciate it very much......that worked. Really appreciate it. – Rich Petersen Feb 07 '23 at 14:22