Home > Mobile >  Problems with Linq/XML query
Problems with Linq/XML query

Time:04-20

So I have this XML file:

<student_update date="2022-04-17" program="PMM" checksum="20021621">
    <transaction>
        <program>PMM</program>
        <student_no>10010800</student_no>
        <course_no>*</course_no>
        <registration_no>111</registration_no>
        <type>2</type>
        <grade>100</grade>
        <notes>Update Grade Test</notes>
    </transaction>
    <transaction>
        <program>PMM</program>
        <student_no>10010821</student_no>
        <course_no>M-50033</course_no>
        <registration_no>*</registration_no>
        <type>1</type>
        <grade>*</grade>
        <notes>Register Course Test</notes>
    </transaction>
</student_update>

And I am trying to run a query against it where the result set should only include transaction elements whose type element is 1 and grade element is “*”, OR whose type element is 2 and grade element is between 0 and 100 inclusive.

The query I have come up with so far is this:

XDocument xDocument = XDocument.Load(inputFileName);

  XElement root = xDocument.Element("student_update");

   IEnumerable<XElement> transactionElements = xDocument.Descendants().Where(x => x.Name == "transaction");

    IEnumerable<XElement> gradeForCourseElement = numTypeElement.Where(x => Int32.Parse(x.Element("type").Value) == 1 && x.Element("grade").Value == "*" ||
                                                                       Int32.Parse(x.Element("type").Value) == 2 && Int32.Parse(x.Element("grade").Value) <= 100);

but it doesn't seem to be liking my way of doing this. I am looking for some advice on how to achieve the requested results. Thanks!

CodePudding user response:

The main thing you've probably missed is that first of all you have to get all descendand elements of the document. Assuming that we want to query from a root element of a document, the code below should work.

This part int.Parse(_.Element("grade")?.Value) <= 100 must be written more carefully.

var xml = "%your xml goes here%";

using (var textReader = new StringReader(xml))
{
    using (var xmlTextReader = new XmlTextReader(textReader))
    {
        var xDoc = XDocument.Load(xmlTextReader);
        var result = xDoc.Descendants()
            .Where(_ => _.Name.LocalName == "transaction"
            &&
            (
                _.Element("type")?.Value == "1" && _.Element("grade")?.Value == "*"
                 ||
                 _.Element("type")?.Value == "2" && int.Parse(_.Element("grade")?.Value) <= 100
            )
            )
            .ToList();
    }
}
  • Related