简体   繁体   中英

Linq XML query with nested loop

I would like to read below XML and print the output in following order. Can you pls help with Query?

在此处输入图片说明

10 Subject1 A1 10 Subject2 B1 10 Subject3 C1 20 Subject1 B2 20 Subject2 A1 20 Subject3 C2

Thanks in advance

Here an example how you can query in the form you want:

XDocument doc = XDocument.Load("test.xml");
var query = from l in doc.Descendants("L1")
            let id = l.Attribute("id").Value
            from subject in l.Descendants("Subject")
            select new
            {
                Id = id,
                SubjectName = (string)subject.Attribute("SubjectName"),
                Score = (string)subject.Attribute("Score")
            };

foreach (var result in query)
{
    Console.WriteLine(result);
}

Output:

{ Id = 10, SubjectName = Subject1, Score = A1 }
{ Id = 10, SubjectName = Subject2, Score = B1 }
{ Id = 10, SubjectName = Subject3, Score = C1 }
{ Id = 20, SubjectName = Subject1, Score = B2 }
{ Id = 20, SubjectName = Subject2, Score = A1 }
{ Id = 20, SubjectName = Subject3, Score = C2 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM