Accept values ​​from an XML document into an array of strings

I am trying to take values ​​from an XML file and put them in an array of strings. Here is the code I use for this:

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

But whenever I use it, I get a NullReferenceException:

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

From 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 The XML file is used here.

<?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>
+3
source share
4 answers

XML has an element name. You are trying to read an attribute name. No, so you get nullback. Make the appropriate changes.

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

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

"name" is not a service attribute. This is a child.

+3
source

name Service, . GetStringArray :

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

node :

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

All Articles