从 XML 文档中获取值到字符串数组

Psy*_*der 4 c# xml linq xpath

我正在尝试从 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();
}
Run Code Online (Sandbox Code Playgroud)

但每当我使用它时,我都会在这里得到一个 NullReferenceException :

foreach (string @string in query)
    WeatherServicesCBO.Items.Add(@string);
Run Code Online (Sandbox Code Playgroud)

该方法的:

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);
}
Run Code Online (Sandbox Code Playgroud)

编辑这是正在使用的 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>
Run Code Online (Sandbox Code Playgroud)

Jef*_*ado 5

XML 有一个name 元素。您正在尝试读取该name 属性。没有了所以你就回去吧null。进行适当的更改。

var services = from service in doc.Descendants("Service")
                select (string)service.Element("name");
Run Code Online (Sandbox Code Playgroud)