-1

I have the following xml code and would like to fetch the sheltertype of value "Loft" and "Condos" under Shelters to list in Xelement.

<Shelters>
            <Shelter>
              <ShelterType>Loft</ShelterType>
                <Price>250/500</Price>
                <Area>250/500</Area>
                <ScreenDisplayText>$250,000 / $500,000</ScreenDisplayText>
              </Shelter>
            <Shelter>
              <ShelterType>TownHouse</ShelterType>
                <Price>250/500</Price>
                <Area>250/500</Area>
                <ScreenDisplayText>$250,000 / $500,000</ScreenDisplayText>
              </Shelter>
            <Shelter>
              <ShelterType>Condos</ShelterType>
                <Price>250/500</Price>
                <Area>250/500</Area>
                <ScreenDisplayText>$250,000 / $500,000</ScreenDisplayText>
              </Shelter>
               <Shelter>
              <ShelterType>apartment</ShelterType>
                <Price>250/500</Price>
                <Area>250/500</Area>
                <ScreenDisplayText>$250,000 / $500,000</ScreenDisplayText>
              </Shelter>
            ---

</Shelters>

I tried with Descendants and I got null value. Looking for Linq with XElement to work on it. Kindly help.

CuriousDev
  • 49
  • 6

2 Answers2

0

I believe this would give you the desired result. This is pulled from an example on another post located here modified to your question, LINQ to read XML

XDocument xdoc = XDocument.Load("Data.xml");
var lv1s = from lv1 in xdoc.Descendants("Shelter")
           select new
           {
                ShelterType = lv1.Element("ShelterType").Value
           };
foreach (var lv in lv1s)
{
    Console.WriteLine(lv.ShelterType);
}
Community
  • 1
  • 1
Bearcat9425
  • 1,580
  • 1
  • 11
  • 12
0

Try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            List<XElement> sheltertype = doc.Descendants("Shelter")
                .Where(x => (x.Element("ShelterType").Value == "Loft") || (x.Element("ShelterType").Value == "Condos")).ToList();
        }
    }
}
​
jdweng
  • 33,250
  • 2
  • 15
  • 20