我正在尝试从XML文件中获取值并将它们放入一个字符串数组中。这是我用来完成此操作的代码:
public static string[] GetStringArray(string path)
{
var doc = XDocument.Load(path);
var services = from service in doc.Descendants("Service")
select (string)service.Attribute("name");
return services.ToArray();
}
但是每次我使用它时,我会在这里遇到NullReferenceException错误:
foreach (string @string in query)
WeatherServicesCBO.Items.Add(@string);
这种方法的作用是:
public void InitializeDropDown(string XmlFile, string xpath)
{
//string[] services = { "Google Weather", "Yahoo! Weather", "NOAA", "WeatherBug" };
string[] services = GetStringArray("SupportedWeatherServices.xml");
IEnumerable<string> query = from service in services
orderby service.Substring(0, 1) ascending
select service;
foreach (string @string in query)
WeatherServicesCBO.Items.Add(@string);
}
编辑 这是正在使用的 XML 文件
<?xml version="1.0" encoding="utf-8" ?>
<SupportedServices>
<Service>
<name>Google Weather</name>
<active>Yes</active>
</Service>
<Service>
<name>WeatherBug</name>
<active>No</active>
</Service>
<Service>
<name>Yahoo Weather</name>
<active>No</active>
</Service>
<Service>
<name>NOAA</name>
<active>No</active>
</Service>
</SupportedServices>