LINQ讀取簡單的XML資料

暖楓無敵發表於2012-08-02
<Countries>
  <Country>
    <Name>Germany</Name>
    <Flag>../Images/Germany.png</Flag>
    <ID>1</ID>
    <Description>Germany Description</Description>
    <Capital>Berlin</Capital>
  </Country>
  <Country>
    <Name>Grece</Name>
    <Flag>../Images/Greece.png</Flag>
    <ID>2</ID>
    <Description>Grece Description</Description>
    <Capital>Athens</Capital>
  </Country>
  <Country>
    <Name>France</Name>
    <Flag>../Images/France.png</Flag>
    <ID>3</ID>
    <Description>France Description</Description>
    <Capital>Paris</Capital>
  </Country>
  <Country>
    <Name>Italy</Name>
    <Flag>../Images/Italy.png</Flag>
    <ID>4</ID>
    <Description>Italy Description</Description>
    <Capital>Rome</Capital>
  </Country>
  <Country>
    <Name>Spain</Name>
    <Flag>../Images/Spain.png</Flag>
    <ID>5</ID>
    <Description>Spain Description</Description>
    <Capital>Madrid</Capital>
  </Country>
  <Country>
    <Name>UK</Name>
    <Flag>../Images/UK.png</Flag>
    <ID>6</ID>
    <Description>UK Description</Description>
    <Capital>London</Capital>
  </Country>
</Countries>

public class XmlCountryRepository : ICountryRepository
{
        private static List<CountryData> countryList = null;

        static XmlCountryRepository()
        {
            XDocument loadedData = XDocument.Load("CountriesXML.xml");

            var data = from query in loadedData.Descendants("Country")
              select new CountryData
              {
                  Name = (string)query.Element("Name"),
                  Flag = (string)query.Element("Flag"),
                  Description = (string)query.Element("Description"),
                  Capital = (string)query.Element("Capital"),
                  ID = (int)query.Element("ID"),
              };
            countryList = data.ToList();
        }

        public IList<CountryData> GetCountryList()
        {
            return countryList;
        }

        public CountryData GetCountryById(int id)
        {
            return countryList.FirstOrDefault(c => c.ID == id);
        }
    }


相關文章