Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]");
like image 362
PsychoCoder Avatar asked Jan 17 '26 09:01

PsychoCoder


1 Answers

The XPath should be //Service/name

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

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

like image 112
Alex Aza Avatar answered Jan 19 '26 21:01

Alex Aza



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!