C# linq到xml的问题

C# linq到xml的问题,c#,linq-to-xml,C#,Linq To Xml,我可能遗漏了一些明显的信息,但在我的Linq to xml查询中出现了“对象引用未设置为对象的实例”空错误 下面是xml的一个示例 <airport> <station> <city>Rutland</city> <state>VT</state> <country>US</country> <icao>KRUT</icao> <lat>43

我可能遗漏了一些明显的信息,但在我的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>

我已经看了一整天了,尝试了很多东西,但是没有运气。有人能帮助这个密集的程序员吗?

城市和所有其他值都在车站内,不是机场的直接后代

也许一些缩进可以揭示这个问题

<airport>
  <station>
    <city>Rutland</city>
    <state>VT</state>
    <country>US</country>
    <icao>KRUT</icao>
    <lat>43.52999878</lat>
    <lon>-72.94999695</lon>
  </station>
</airport>
subjects()
提供当前节点下任何级别的所有元素,而
Element()
只查看当前节点的直接子级。由于使用
元素()
调用请求的所有值都是
站的子项,而不是
机场的子项,因此对
元素()
的调用不返回任何对象。使用
.Value
解除对它们的引用会导致异常

如果将查询更改为以下内容,则它应该可以工作:

XDocument geoLocation = XDocument.Load("myTestGeo.xml");

var currLocation = from geo in geoLocation.Descendants("station")
                   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
                   };

我看到了,但如果我在station上查询,我会得到相同的空错误。我没有带linq的.net framework,所以我无法自己测试。请参阅与您尝试实现的非常相似的示例。您确定
myTestGeo.xml
包含您在示例中指出的xml吗?这是一个来自weather underground的xml文件,下面还有其他节点,但在此之前我使用linq to xml读取xml文件。机场模式下的节点也是,但我对这些不感兴趣。如果你愿意,我会发布一个更完整的文件片段。
XDocument geoLocation = XDocument.Load("myTestGeo.xml");

var currLocation = from geo in geoLocation.Descendants("station")
                  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
                  };
XDocument geoLocation = XDocument.Load("myTestGeo.xml");

var currLocation = from geo in geoLocation.Descendants("station")
                   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
                   };