ScottinTexas
ScottinTexas

Reputation: 181

Get a list of ID Attributes from an XML File C#

I am trying to get a list of the Service IDs from the xml file below.

  <Settings>
<SomeTag>Some inner text</SomeTag>
<Services ID="Downtown Location">
    <Service ID="22923">Basic</Service>
    <Service ID="22926">Basic + 2</Service>
    <Service ID="22927">Basic + 3</Service>
    <Service ID="22928">Basic + 4</Service>
    <Service ID="22929">Basic + 5</Service> 
</Services>
<MoreTags>
    <ATag></ATag>
    <ATag></ATag>
    <ATag></ATag>
    <ATag></ATag>
</MoreTags>
</Settings>

I have tried several methods I found on line but each one has had some sort of problem. This was my last attempt.

          List<string> ServiceList = new List<string>();
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(AppDomain.CurrentDomain.BaseDirectory + @"\Settings.xml");
            XmlNodeList nodes = xdoc.DocumentElement.SelectNodes("/Services/Service");
            foreach (XmlNode node in nodes)
            {
                ServiceList.Add(node.Attributes["ID"].Value);
            }
            return ServiceList; 

In this case the nodes has no items. I have tried several variations of SelectNodes but still have no items. Earlier I tried XDocument and a LINQ query. I would prefer to do it that way, but I have yet to find an example that collects the IDs.

Upvotes: 2

Views: 2462

Answers (3)

Luke Woodward
Luke Woodward

Reputation: 64979

The fix is to remove the leading / in the XPath expression in this line

            XmlNodeList nodes = xdoc.DocumentElement.SelectNodes("/Services/Service");

to give you

            XmlNodeList nodes = xdoc.DocumentElement.SelectNodes("Services/Service");

An XPath expression beginning with / starts the search for matching elements from the root of the document. You however have navigated to the document element and want to start the search from there.

Upvotes: 0

Jonathan Applebaum
Jonathan Applebaum

Reputation: 5986

Here is an example with System.Xml.Linq:

static void Main(string[] args)
{
    var xmldoc = System.Xml.Linq.XDocument.Load(@"YOUR FILE");

    foreach (var name in xmldoc.Descendants("Services").Elements()
                        .Select(x => new { Name = x.Name, Value = x.Value, ID=x.Attribute("ID")
                       }))
    {       
       Console.WriteLine(name.ID.Value);
    }

    Console.ReadLine();
}

OUTPUT:

22923
22926
22927
22928
22929

Upvotes: 2

Anu Viswan
Anu Viswan

Reputation: 18153

To be begin with, I believe it was a typo that you missed out the closing "Settings" Tag. To capture the ID using Linq to Xml, you could use.

XElement xmlNode = XElement.Load(filePath);
var result = xmlNode.Descendants("Service").Select(x=>x.Attribute("ID").Value);

Sample Output

enter image description here

Upvotes: 3

Related Questions