Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take values from XML document to string array

Tags:

c#

xml

linq

xpath

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(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 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>
like image 955
PsychoCoder Avatar asked Oct 28 '25 10:10

PsychoCoder


1 Answers

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");
like image 170
Jeff Mercado Avatar answered Oct 29 '25 23:10

Jeff Mercado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!