C# 将XML文档中的值转换为字符串数组
我试图从XML文件中获取值,并将它们放入字符串数组中。下面是我用来完成此任务的代码:C# 将XML文档中的值转换为字符串数组,c#,xml,linq,xpath,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("n
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);
}
public void InitializeDropDown(字符串XmlFile,字符串xpath)
{
//字符串[]服务={“谷歌天气”、“雅虎天气”、“NOAA”、“WeatherBug”};
string[]services=GetStringArray(“SupportedWeatherServices.xml”);
IEnumerable query=来自服务中的服务
orderby服务。子字符串(0,1)升序
选择服务;
foreach(查询中的字符串@string)
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>
谷歌天气
对
风虫
不
雅虎天气
不
诺阿
不
选择(字符串)服务属性(“名称”)代码>
“名称”不是服务的属性。它是一个子元素。name
不是服务的属性,而是一个子元素。您应该将GetStringArray
查询修改为:
var services = from service in doc.Descendants("Service")
select service.Element("name").Value;
XML有一个名称元素。您正在尝试读取名称
属性。没有,因此返回null
。进行适当的更改
var services = from service in doc.Descendants("Service")
select (string)service.Element("name");
获取数组中的节点列表:
XmlDocument xDocument;
xDocument.Load(Path);
var xArray = xDocument.SelectNodes("SupportedServices/Service/name");
那么,如果每个服务都有一个名称,您是否查看了XML?在创建查询时,缺少的查询不会显示,但在迭代时会显示。