2009-06-30 46 views
1

我得到NRE錯誤,它說:「對象引用未設置爲對象的實例。」C#中的NullReferenceException處理XML

從下面的代碼:

select new 
        { 
         ICAO = station.Element("icao").Value, 
        }; 

整個腳本是:

XDocument xmlDoc = XDocument.Load(@"http://api.wunderground.com/auto/wui/geo/GeoLookupXML/index.xml?query=94107"); 

    var stations = from station in xmlDoc.Descendants("station") 
        select new 
        { 
         ICAO = station.Element("icao").Value, 
        }; 
    lblXml.Text = ""; 
    foreach (var station in stations) 
    { 
     lblXml.Text = lblXml.Text + "ICAO: " + station.ICAO + "<br />"; 
    } 

    if (lblXml.Text == "") 
     lblXml.Text = "No Results."; 
    } 

我不明白爲什麼不創建站對象並設置國際民航組織值。任何有關未來XML和C#參考的想法/提示?

+0

爲什麼在ICAO = station.Element(「Icao」)之後有逗號?價值線?你沒有得到多個元素...... – curtisk 2009-06-30 16:04:28

+0

它並沒有受到傷害,它可能是代碼的實際部分要大得多。如果這實際上完成了所有工作,那麼在新的{...}內也不需要它,您可以直接選擇icao。 – 2009-06-30 16:14:24

回答

9

似乎只有機場站有國際民航組織的元素。這應該爲你工作:

var stations = from airport in xmlDoc.Descendants("airport") 
       from station in airport.Elements("station") 
       select new 
       { 
        ICAO = station.Element("icao").Value, 
       }; 

您可以改爲添加一個where條件得到異常的周圍:

var stations = from station in xmlDoc.Descendants("station") 
       where station.Element("icao") != null 
       select new 
       { 
        ICAO = station.Element("icao").Value, 
       }; 

此外,您還可以拉這樣的值,以防止一個例外,雖然它會返回衆多空的記錄,你可能會或可能不會想:

ICAO = (string)station.Element("icao") 

你可以做各種其他類型,不僅爲字符串。

0

我不認爲xmlDoc.Descendants("station")正在返回你所期待的。你應該在這裏檢查結果。這就是爲什麼station.Element(「icao」)返回null。

0

該URL似乎沒有返回XML數據,我懷疑這會導致您的節點引用返回空值。

0

嘗試這樣:

var stations = from station in xmlDoc.Elements("station") 
select new 
{ 
    ICAO = station.Element("icao").Value, 
}; 
1

您示例中的XML文件返回一些station元素,但沒有icao後代,因此有時station.Element("icao")將返回空值。

相關問題