Linq 读取简单的XML数据
在项目开发中常用到这些,记录下来,以后忘记了,来查询
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); } }
<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>