我正在尝试从 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>
最佳答案
XML 有一个名称
元素。您正在尝试读取 name
属性。没有,所以你得到 null
。进行适当的更改。
var services = from service in doc.Descendants("Service")
select (string)service.Element("name");
关于c# - 从 XML 文档中获取值到字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6390785/