2010-03-05 64 views
0

我可能錯過了一些明顯的東西,但是我在Linq to xml查詢中得到'對象引用未設置爲對象的實例'null錯誤。linq到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 
           }; 

我一直在尋找這一切的一天,想很多東西,但沒有運氣。有人可以幫助這個密集的程序員嗎?

回答

1

城市和所有其他值是站內,並不是機場的直接後代。

也許一些縮進爲這個問題提供了一些啓示。

<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("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 
        }; 
+0

我看到了,但如果我站上查詢我得到同樣的錯誤無效。 – 2010-03-05 17:55:26

+0

我沒有.net框架與linq,所以我不能測試自己。請參閱http://www.linqhelp.com/linq-tutorials/linq-to-xml-displaying-and-filtering-data-from-xml-file-in-c/,這個例子與您所看到的非常相似試圖實現。 – 2010-03-05 18:05:18

+0

你確定'myTestGeo.xml'具有你在這個例子中指出的XML嗎? – 2010-03-05 18:07:52

0

Descendants()給所有元素在當前節點之下的任何水平,而Element()只着眼於當前節點的直接孩子。由於您請求撥打Element()的所有值都是station的子項,而不是airport,因此對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 
        };