0

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

enter image description here

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

Thanks in advance

2
  • I don't get how you expect Subject1 C1 to come out of that XML? Commented May 7, 2012 at 20:05
  • Sorry, there was typo for Subject 3. I have been able to load the Xdocument and declare var with XElement ID but never used Linq before. I can do this in SQL server, but the issue is I lose much of the formatting hence trying to do using C# Commented May 7, 2012 at 20:33

1 Answer 1

0

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 }
Sign up to request clarification or add additional context in comments.

2 Comments

For more inline madness could use a (query).ToList().ForEach(item => Console.WriteLine(item)), substituting query with the linq query you suggested. ;)
Hello, please suggest what changes should be made to display the date in the output. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.