2009-06-30 48 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")将返回空值。

相关问题