使用Linq使用C#更新XML
我的XML文件结构
1 True Star Wars Figures LukeSkywalker
通过ITEMID从XML读取数据
XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("data.xml")); var items = from item in xmlDoc.Descendants("item") where item.Element("itemID").Value == itemID select new { itemID = item.Element("itemID").Value, isGadget = bool.Parse(item.Element("isGadget").Value), name = item.Element("name").Value, text1 = item.Element("text1").Value, } foreach (var item in items) { .... }
如何按itemID更新XML数据? 谢谢!
要更新xml,请使用XElement的SetElementValue方法:
var items = from item in xmlDoc.Descendants("item") where item.Element("itemID").Value == itemID select item; foreach (XElement itemElement in items) { itemElement.SetElementValue("name", "Lord of the Rings Figures"); }
编辑:是的,我尝试了你的例子,它将更新的数据保存到文件中。 使用XDocument的Save方法保存更新的xml,这是我尝试的代码:
string xml = @" -
1 True Star Wars Figures LukeSkywalker "; XDocument xmlDoc = XDocument.Parse(xml); var items = from item in xmlDoc.Descendants("item") where item.Element("itemID").Value == "1" select item; foreach (XElement itemElement in items) { itemElement.SetElementValue("name", "Lord of the Rings Figures"); } xmlDoc.Save("data.xml");
要更新XElement的xml use元素方法方法:
XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("data.xml")); var items = (from item in xmlDoc.Descendants("item") where item.Element("itemID").Value == itemID select item).ToList(); foreach (var item in items) { item.Element("itemID").Value=NewValue; bool.Parse(item.Element("isGadget").Value)=Newvalue; item.Element("name").Value=Newvalue; item.Element("text1").Value=Newvalue; } xmlDoc.Save(HttpContext.Current.Server.MapPath("data.xml"));
要么
XDocument xmlDoc = XDocument.Load(HttpContext.Current.Server.MapPath("data.xml")); foreach (var item in (from item in xmlDoc.Descendants("item") where item.Element("itemID").Value == itemID select item).ToList()) { item.Element("itemID").Value=NewValue; bool.Parse(item.Element("isGadget").Value)=Newvalue; item.Element("name").Value=Newvalue; item.Element("text1").Value=Newvalue; } xmlDoc.Save(HttpContext.Current.Server.MapPath("data.xml"));
您可以获得动态信息并在按钮单击事件中更新这些更改,首先检查代码存在时的页面加载
if(!Page.IsPostBack) { .... }
您的查询将投射到匿名类型。 如果您只想修改元素本身,您需要以下内容:
var items = from item in xmlDoc.Descendants("item") where item.Element("itemID").Value == itemID select item;
否则称为:
var items = xmlDoc.Descendants("item") .Where(item => item.Element("itemID").Value == itemID);
我建议您也调用ToList()
,以便在开始修改之前执行整个查询并将结果存储在列表中:
var items = xmlDoc.Descendants("item") .Where(item => item.Element("itemID").Value == itemID) .ToList();