C# 使用Linq用C更新XML
我的XML文件结构C# 使用Linq用C更新XML,c#,xml,linq,C#,Xml,Linq,我的XML文件结构 <items> <item> <itemID>1</itemID> <isGadget>True</isGadget> <name>Star Wars Figures</name> <text1>LukeSkywalker</text1> </item> </items> 如何通过itemID
<items>
<item>
<itemID>1</itemID>
<isGadget>True</isGadget>
<name>Star Wars Figures</name>
<text1>LukeSkywalker</text1>
</item>
</items>
如何通过itemID更新XML数据?
谢谢 您的查询正在投影到匿名类型。如果只想修改图元本身,则需要类似以下内容:
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();
要更新xml,请使用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");
}
编辑:是的,我尝试了你的例子,它将更新的数据保存到文件中。使用保存更新的xml,以下是我尝试的代码:
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");
要更新xml,请使用XElement的元素方法:
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"));
或
您可以从动态表单中获取信息,并更新按钮单击事件中的更改。首先,您可以检查页面加载是否存在以下代码
if(!Page.IsPostBack) { .... }
能否提供一个简单的调用toList来更新xml的示例?我是否需要使用foreach循环来设置ElementValue?调用ToList不会更新XML,是的,您需要使用foreach。但是,您还没有说明如何更新XML,因此举个例子有点棘手。不确定更新XML文档的选项是什么。也许你可以建议最有效的方法我们真的可以向ToList推荐电话吗?我已经看到初级开发人员在他们的头脑中意识到,无论使用情况如何,在每次查询之后都需要一个ToList或ToArray。在我看来,应该有更好的使用指南。毕竟,这是使用List.ForEach的网关。严峻的不工作。也许我错过了什么。我必须添加xmlDoc.Savedata.xml吗?即使使用xmlDoc.Save,它仍然不会更新.Canavar,我希望直接更新xml文件,而不必首先将其转换为字符串。谢谢我不明白为什么这些LINQ到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) { .... }