开发者

C# XML parsing - skipping null tags in some 'items'

how are we toda开发者_StackOverflow社区y?

I use this code to read an XML file and place the results in my for each loop afterwards.

 var document = XDocument.Load(e.Result);
 if (document.Root == null)
            return;

        var georss = XNamespace.Get("http://www.georss.org/georss");

 var events1 = from ev1 in document.Descendants("channel").Elements("item")

                      let values = ev1.Element(georss + "point").Value.Split(' ')
                      select new       
                      {
                      Latitude = double.Parse(values[0], CultureInfo.InvariantCulture),
                      Longitude = double.Parse(values[1], CultureInfo.InvariantCulture), 
                      Title = (ev1.Element("title").Value),
                                                }; 


          blahblahMethod();

        foreach (var ev1 in events1)
        {
       blah blah do stuff
       }

Ok, so there we are, I grab the contents of the "point" and "title" tags which are nested inside each parent "item" tag in the XML file. There are say 10 items in the XML file. The problem is, not all of the 'items' contain the "point" tag. It is completely missing from some items; so there would be just the "title" tag.

When the XML reader reaches a one of these items, it throws a 'NullReferenceException was unhandled'. So its pretty obvious whats happening. Im having trouble working out a way round this. I thought of some 'if' statement that if it gets to a null tag then it will skip that, but cant seem to fit anything in which VS accepts and doesnt throw some error. Any help appreciated. (Beginner here, be gentle please! :-) )


I have a loathing for the Query language syntax and prefer to use extension methods directly so I would tweak your from line like this:-

from ev1 in document.Descendants("channel").Elements("item")
    .Where(e => e.Element(georss + "point") != null)

you could probably add a where clause in the query just after the from to do the same thing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜