使用LINQ更新XML用C# [英] Update XML with C# using Linq
本文介绍了使用LINQ更新XML用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
//MY XML FILE STRUCTURE
<items>
<item>
<itemID>1</itemID>
<isGadget>True</isGadget>
<name>Star Wars Figures</name>
<text1>LukeSkywalker</text1>
</item>
</items>
//TO READ DATA FROM XML BY ITEMID
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数据?
谢谢!
How to update XML data by itemID? Thanks!
推荐答案
要更新XML使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.setelementvalue.aspx\">SetElementValue该的XElement的方法:
To update your xml use SetElementValue method of the XElement :
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 的保存方法更新后的XML,这里是code,我尝试:
EDIT : Yes, I tried your example and it saves updated data to the file. Save your updated xml with Save method of the XDocument, here is the code that I tried :
string xml = @"<items>
<item>
<itemID>1</itemID>
<isGadget>True</isGadget>
<name>Star Wars Figures</name>
<text1>LukeSkywalker</text1>
</item>
</items>";
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");
这篇关于使用LINQ更新XML用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文