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

标签 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>

最佳答案

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/

相关文章:

php - 如何在 PHP 中获取 DOMDocument 中的特定标签?

c# - 将图像从 xml 中的字节转换为 word 文档

输出 XML 文件的 Java 程序 - 多个问题

c# - 如何使用 LINQ 从 IEnumerable 中选择随机项

c# - 是否可以通过内存映射文件将实例 "pointer"传递给另一个进程?

c# - 在后面的代码中多次绑定(bind)到 TextBlock - 我在哪里弄错了?

c# - Linq 获取表中条目最多的员工的 ID

c# - 用于删除 ID 不等于 ID 列表的所有对象的 LINQ 查询现在可以正常工作

c# - 自定义字典 ​​TryGetValue 找不到键

c# - Xamarin iOS Google Maps SDK - mapView.AddObserver() 异常