Search code examples
c#xmlwindows-phone-8linq-to-xml

Parsing XML in Windows Phone 8


I have a xml file which looks like below.

<sections>
   <section>
      <name>QLD Mosques</name>
      <stations>
         <station>
            <id>101</id>
            <pn>true</pn>
            <name>Kuraby Mosque</name>
            <url>http://sb2110.ultrastream.co.uk/kuraby</url>
            <icon>...</icon>
         </station>
         <station>
            <id>102</id>
            <pn>true</pn>
            <name>Gold Coast Mosque</name>
            <url>http://sb2110.ultrastream.co.uk/goldcoast</url>
            <icon>http://www.juju.net.au/mosquereceivers/images/icons/gc.jpg</icon>
         </station>
         <station>...</station>
      </stations>
   </section>
   <section>
      <name>NZ Mosques</name>
      <stations>...</stations>
   </section>
   <section>
      <name>Islamic Radio Stations</name>
      <stations>...</stations>
   </section>
</sections>

I want get show all the station name which has "section" named "QLD Mosques". For example my result will be "Kuraby Mosque,Gold Coast Mosque,...". How can i achieve the result??

N:B: I can show the names under "section" tag(which gives the result QLD Mosques,NZ Mosques,Islamic Radio Stations) by using these code:

public static List<MyData> channel_main_list = new List<MyData>();

    public MainChannelList()
    {
        InitializeComponent();


        WebClient client = new WebClient();
        client.OpenReadCompleted += client_OpenReadCompleted;
        client.OpenReadAsync(new Uri("http://www.juju.net.au/mosquereceivers/Stations.xml",UriKind.Absolute));

    }

    void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        if (e.Error != null)
            return;

        Stream str = e.Result;

        string node = "section";

        XDocument loadedData = XDocument.Load(str);

        try
        {
            foreach (var item in loadedData.Descendants(node))
            {

                try
                {
                    MyData m = new MyData();
                    m.channel_name = item.Element("name").Value;

                    channel_main_list.Add(m);
                }
                catch (Exception)
                {

                    MessageBox.Show("Problem");
                }



            }

            listBox.ItemsSource = channel_main_list;

        }
        catch (Exception)
        {
            MessageBox.Show("Connectivity Problem");
        }
    }

Solution

  • This is one possible way, assuming that the XML structure is consistent and name being searched is always found :

    var result = loadedData.Descendants("section")
                           .Where(o => (string)o.Element("name") == "QLD Mosques")
                           .Elements("stations")
                           .Elements("station")
                           .Elements("name");
    

    Dotnetfiddle Demo