gpt4 book ai didi

c# - C# 处理 XML 中的 NullReferenceException

转载 作者:太空宇宙 更新时间:2023-11-03 17:47:25 24 4
gpt4 key购买 nike

我收到 NRE 错误:“对象引用未设置到对象的实例。”

来自以下代码:

  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.";
}

我不明白为什么它不创建站对象并设置 ICAO 值。对 future 的 XML 和 C# 引用有什么想法/提示吗?

最佳答案

似乎只有机场站有 icao 元素。这应该适合你:

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")

您可以为各种其他类型执行此操作,而不仅仅是字符串。

关于c# - C# 处理 XML 中的 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1064482/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com