后代的Xdocument问题 [英] Xdocument problem with descendants

查看:71
本文介绍了后代的Xdocument问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string myTown = document.Element("GeocodeResponse").Element("result").Elements("address_component").Where(x => (string)x.Element("type").Value == "locality").Select(x => x.Element("long_name").Value).First();



工作正常,但



works fine but

List<GeocoderLocation> geoList = new List<GeocoderLocation>();
                        geoList = (from result in document.Descendants("result")
                                  select new GeocoderLocation
                                  {
                                      Town = result.Elements("address_component").Where(x => (string)x.Element("type").Value == "locality").Select(x => x.Element("long_name").Value).First(),
                                      
                                  }).ToList();


才不是.它引发异常InvalidOperationException Sequence不包含任何元素.

这是尝试解析Google http://maps的地理编码. googleapis.com/maps/api/geocode/xml?address=miry%20ln%20uk&sensor=false [


does not. It throws exception InvalidOperationException Sequence contains no elements.

This is attempt to parse geocode from google http://maps.googleapis.com/maps/api/geocode/xml?address=miry%20ln%20uk&sensor=false[^]
Why?

推荐答案

我的糟糕.我以为它是第一次抛出异常.但这没有,问题的原因是某些节点不包含邮政编码或其他内容,因此为空.

解决方案:代替.First()使用.FirstOrDefault()
My bad. I assumed that it was throwing exception on first go. But it didn''t and the cause of problem was that some nodes didn''t contain postcode or something else and therefore being empty.

Solution: instead of .First() use .FirstOrDefault()


这篇关于后代的Xdocument问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆