最近在做天气预报应用,这个应用中需要用到Xml来存储关注的城市列表,保存一下代码,方便以后使用,也给博友们一个参考:
其中:添加关注城市的操作代码是:
其实就是,
(1)先把数据从CareCityCode.xml文档中查询出来,放在集合A中,然后删除该文档。
(2)把新关注的城市添加到集合A中,
(3)把集合A中的数据再新建一个CareCityCode.xml,保存到该xml文档中。
#region 获取关注城市ID列表 --GetCareCityList /// <summary> /// 获取关注城市ID列表 /// </summary> /// <returns></returns> public static ObservableCollection<City> GetCareCityList() { ObservableCollection<City> list = new ObservableCollection<City>(); using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { if (isf.FileExists("CareCityCode.xml")) { using (IsolatedStorageFileStream isoStream = isf.OpenFile("CareCityCode.xml", FileMode.Open, FileAccess.Read)) { XElement xel = XElement.Load(isoStream); //MessageBox.Show("Xml文档的数据"+xel.ToString()); var citys = from city in xel.Descendants("CityCode") //orderby "DateTime" descending select city; foreach (var city in citys) { list.Add(new City { CityID = city.Element("ID").Value , CityName=city.Element("Name").Value}); } } } } return list; } #endregion
#region 添加关注城市ID --AddCareCity /// <summary> /// 添加关注城市ID /// </summary> /// <param name="CityID"></param> public static void AddCareCity(string CityID,string CityName) { using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { if (isf.FileExists("CareCityCode.xml")) { ObservableCollection<City> list = GetCareCityList(); //判断添加的要关注的城市是否已经存在 foreach (var City in list) { if (City.CityID == CityID) { MessageBox.Show("已在关注列表中!"); return; } } list.Add(new City() { CityID=CityID, CityName=CityName}); isf.DeleteFile("CareCityCode.xml"); using (IsolatedStorageFileStream isoStream = isf.OpenFile("CareCityCode.xml", FileMode.OpenOrCreate, FileAccess.Write)) { XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("CityCodes")); foreach (City temp in list) { doc.Element("CityCodes").Add(new XElement("CityCode", new XElement("ID", temp.CityID), new XElement("Name",temp.CityName))); } MessageBox.Show(doc.ToString()); doc.Save(isoStream); } } else { using (IsolatedStorageFileStream isoStream = isf.OpenFile("CareCityCode.xml", FileMode.OpenOrCreate, FileAccess.Write)) { XElement xel = new XElement("CityCodes", new XElement("CityCode", new XElement("ID", CityID), new XElement("Name",CityName)) ); XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), xel); doc.Save(isoStream); MessageBox.Show(doc.ToString()); } } } } #endregion
删除代码:明天再贴,
而且我感觉这种方法很麻烦的,,,稍后会介绍一种比较简单的方法。