簡體   English   中英

將值從XML文檔獲取到字符串數組

[英]Take values from XML document to string array

我正在嘗試從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 元素 您正在嘗試讀取name 屬性 沒有,所以你得到null 進行適當的更改。

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

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

“name”不是服務的屬性。 它是一個兒童元素。

name不是Service的屬性,而是子元素。 您應該將GetStringArray查詢修改為:

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

在Array中獲取節點列表:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM