PsychoCoder
PsychoCoder

Reputation: 10755

XPath not working as expected

I have an XML document in this format:

<?xml version="1.0" encoding="utf-8" ?>
<SupportedServices>
  <Service>
    <name>Google Weather</name>
    <active>Yes</active>
  </Service>
   ...
</SupportedServices>

And I'm trying to parse the XML file like so:

public void InitializeDropDown(string XmlFile, string xpath)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(XmlFile);

    var rootNode = doc.DocumentElement;

    var serviceList = rootNode.SelectNodes(xpath);

    Parallel.ForEach(serviceList.Cast<XmlNode>(), service =>
    {
        if (Properties.Settings.Default.ServiceActive &&
            Properties.Settings.Default.ServiceName == service.InnerText)
        {
            WeatherServicesCBO.Items.Add(service.InnerText);
        }
    });
}

The issue I'm having is both values (name & active) are selected so it would look like Google WeatherYes, when All I'm wanting is Google Weather. Can someone tell me what's wrong with my XPath (which is here):

InitializeDropDown("SupportedWeatherServices.xml", "descendant::Service[name]");

Upvotes: 3

Views: 563

Answers (1)

Alex Aza
Alex Aza

Reputation: 78457

The XPath should be //Service/name

var serviceList = rootNode.SelectNodes("//Service/name");

or descendant::Service/name, if you like this syntax more.

Upvotes: 4

Related Questions