开发者

Take values from XML document to string array

I'm attempting to take values from a XML file and put them into a string array. Here's the code I'm using to accomplish this:

public static string[] GetStringArray(string path)
{
    var doc = XDocument.Load(pa开发者_高级运维th);

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

    return services.ToArray();
}

But whenever I use it I get a NullReferenceException here:

foreach (string @string in query)
    WeatherServicesCBO.Items.Add(@string);

Of this method:

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);
}

EDIT Here's the XML file being used

<?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>


The XML has a name element. You are attempting to read the name attribute. There is none so you get null back. Make the appropriate changes.

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


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

"name" is not an attribute of service. it is a child element.


name is not an attribute of Service but a child element. You should modify your GetStringArray query to:

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


Get node list in Array:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜