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

4

我正在尝试从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文件,确认每个服务都有名称?如果有一个服务缺失名称,在创建“query”时不会显示出来,但在迭代时会出现问题。 - H H
4个回答

5
XML有一个名为name元素。您试图读取name 属性,但是它不存在,所以您得到了null。请进行相应的更改。
var services = from service in doc.Descendants("Service")
                select (string)service.Element("name");

3

select (string)service.Attribute("name");

“name”不是service的属性,而是子元素。


2

name不是Service的属性,而是一个子元素。你应该修改你的GetStringArray查询为:

var services = from service in doc.Descendants("Service")
               select service.Element("name").Value;

1

获取节点列表到数组中:

XmlDocument xDocument;
xDocument.Load(Path);
var xArray = xDocument.SelectNodes("SupportedServices/Service/name");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接