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);
}
4

3 回答 3

2

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).

于 2012-05-21T19:26:12.217 回答
1

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)
于 2012-05-21T19:20:40.937 回答
1

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 
于 2012-05-21T19:27:45.563 回答