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

时间:2011-06-17 19:24:52

标签: 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();
}

但每当我使用它时,我在这里得到一个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>

4 个答案:

答案 0 :(得分:4)

XML具有name 元素。您正在尝试阅读name 属性。没有,所以你得到null。进行适当的更改。

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

答案 1 :(得分:3)

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

“name”不是服务的属性。它是一个儿童元素。

答案 2 :(得分:2)

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

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

答案 3 :(得分:1)

在Array中获取节点列表:

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