简体   繁体   中英

Linq XML query with nested loop - 1

In this question , if I need to get "date" included in the output, what changes should be made?

When I included

let dt = l.Element("Date").Value

It gives, "Object reference not set to an instance of an object"

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


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

If l doesn't have an Date element, trying to access l.Element("Date").Value will incur an error. You can use a conditional:

var query = from l in doc.Descendants("L1")
        let dt = l.Elements("date").Any() 
                 ? l.Element("date").Value
                 : AnyDefaultValueIWantForDate
        let id = l.Attribute("id").Value
        from subject in l.Descendants("Subject")
        select new
        {
            Date = dt,
            Id = id,
            SubjectName = subject.Attribute("SubjectName").Value,
            Score = subject.Attribute("Score").Value
        };

(I also added the .Value in SubjectName and Score ).

Assuming l is not null then l.Element("Date") is null which would mean that one or more of your L1 elements does not have a child Date element.

The fix would depend on what you want to do with missing dates. If you want to use default(DateTime) as a "magic" date, you could do:

let dt = (l.Element("Date") == null ? default(DateTime) : l.Element("Date").Value)

Looking at your other XML, it does not, as Mr. Skeet mentioned, have anything in the <date> elements. You will need to explicitly handle that if you aren't planning on always having data in there.

You can do something like this:

let dt = l.Element("date") == null ? string.Empty : l.Element("date").Value 

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