Search code examples
c#xmllistxmlreader

Get a list of items from xml according to variable


I am looking to get a list of cities where a country equals a variable in C#

Here is a snippet of my xml

So I would like to load the cities for Afganistan into a list via a variable. Below is the code I have that shows all the values in my xml file.

XmlReader reader = new XmlTextReader(@"Countries_Cities.xml");

    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element && reader.Name == "title")
        {
            string title = reader.ReadElementString();
            Debug.WriteLine("Country Name: " + title);
        }
        if (reader.NodeType == XmlNodeType.Element && reader.Name == "city")
        {
            string city = reader.ReadElementString();
            Debug.WriteLine("* " + city);
       }
    }

Solution

  • Using Xml Linq :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication18
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            public static void Main(String[] args)
            {
                XDocument doc = XDocument.Load(FILENAME);
                string[] cities = doc.Descendants("country").Where(x => (string)x.Element("title") == "Afghanistan").Descendants("city").Select(x => (string)x).ToArray();
            }
        }
    }