linq 到 xml 的问题
我可能遗漏了一些明显的东西,但我在 Linq to xml 查询中收到“对象引用未设置到对象实例”空错误。
这是 xml 的示例
<airport>
<station>
<city>Rutland</city>
<state>VT</state>
<country>US</country>
<icao>KRUT</icao>
<lat>43.52999878</lat>
<lon>-72.94999695</lon>
</station>
</airport>
,这是我的查询,
XDocument geoLocation = XDocument.Load("myTestGeo.xml");
var currLocation = from geo in geoLocation.Descendants("airport")
select new
{
City = geo.Element("city").Value,
State = geo.Element("state").Value,
Country = geo.Element("country").Value,
Station = geo.Element("icao").Value
Lat = geo.Element("lat").Value,
Lon = geo.Element("lon").Value
};
我一整天都在查看它并尝试了很多东西,但没有运气。有人可以帮助这个密集的程序员吗?
I am probably missing something obvious, but I am getting a 'Object reference not set to an instance of an object' null error in my Linq to xml query.
Here is a sample of the xml
<airport>
<station>
<city>Rutland</city>
<state>VT</state>
<country>US</country>
<icao>KRUT</icao>
<lat>43.52999878</lat>
<lon>-72.94999695</lon>
</station>
</airport>
and here is my query
XDocument geoLocation = XDocument.Load("myTestGeo.xml");
var currLocation = from geo in geoLocation.Descendants("airport")
select new
{
City = geo.Element("city").Value,
State = geo.Element("state").Value,
Country = geo.Element("country").Value,
Station = geo.Element("icao").Value
Lat = geo.Element("lat").Value,
Lon = geo.Element("lon").Value
};
I have been looking at this all day and tried lots of things, but no luck. Can someone help this dense programmer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Descendants()
给出当前节点以下任何级别的所有元素,而Element()
仅查看当前节点的直接子节点。由于您通过Element()
调用请求的所有值都是station
的子项,而不是airport
,因此对Element() 的调用
不返回任何对象。使用.Value
取消引用它们会导致异常。如果将查询更改为以下内容,它应该可以工作:
Descendants()
gives all elements at any level below the current node whereasElement()
only looks at direct children of the current node. As all the values you request with theElement()
call are children ofstation
and notairport
, the calls toElement()
return no objects. Dereferencing them with.Value
leads to the exception.If you change your query to the following, it should work:
city 和所有其他值都在 station 内,而不是 airport 的直系后代。
也许一些缩进可以让我们了解这个问题。
这可能会起作用:
city and all the other values are inside station and are not direct descendants of airport.
Perhaps some indentation sheds some light into the issue.
This would probably work: