C# 更新XAttribute值,其中XAttribute Name=X
下面的代码创建了一个包含大量订单信息的XML文件。我希望能够更新这个XML文件中的一个条目,而不是删除所有内容并重新添加所有内容 我知道我能做到:C# 更新XAttribute值,其中XAttribute Name=X,c#,.net,xml,linq,linq-to-xml,C#,.net,Xml,Linq,Linq To Xml,下面的代码创建了一个包含大量订单信息的XML文件。我希望能够更新这个XML文件中的一个条目,而不是删除所有内容并重新添加所有内容 我知道我能做到: xElement.Attribute(attribute).Value = value; 但这将更改与属性保持相同名称的每个属性。例如,当条目的Id等于“jason”时,我如何才能更改某个内容的值?我是否需要加载XML文件,对整个文件进行迭代,直到找到与我要更改的属性相匹配的文件,然后进行更改,然后再次保存该文件 非常感谢您的帮助/建议 XElem
xElement.Attribute(attribute).Value = value;
但这将更改与属性保持相同名称的每个属性。例如,当条目的Id等于“jason”时,我如何才能更改某个内容的值?我是否需要加载XML文件,对整个文件进行迭代,直到找到与我要更改的属性相匹配的文件,然后进行更改,然后再次保存该文件
非常感谢您的帮助/建议
XElement xElement;
xElement = new XElement("Orders");
XElement element = new XElement(
"Order",
new XAttribute("Id", CustomId),
new XAttribute("Quantity", Quantity),
new XAttribute("PartNo", PartNo),
new XAttribute("Description", Description),
new XAttribute("Discount", Discount),
new XAttribute("Freight", Freight),
new XAttribute("UnitValue", UnitValue),
new XAttribute("LineTotal", LineTotal)
);
xElement.Add(element);
xElement.Save(PartNo + ".xml");
以下是我的XML文件的外观:
<?xml version="1.0" encoding="utf-8"?>
<Orders>
<Order Id="V45Y7B458B" Quantity="2" PartNo="5VNB98" Description="New Custom Item Description" Discount="2.00" Freight="2.90" UnitValue="27.88" LineTotal="25.09" />
<Order Id="jason" Quantity="2" PartNo="jason" Description="New Custom Item Description" Discount="2.00" Freight="2.90" UnitValue="27.88" LineTotal="25.09" />
</Orders>
首先,您需要搜索要更新的元素。如果找到它,请进行更新。完成后,请记住将XDocument保存回文件
XDocument doc = ...;
var jason = doc
.Descendants("Order")
.Where(order => order.Attribute("Id").Value == "jason") // find "jason"
.SingleOrDefault();
if (jason != null) // if found,
{
// update something
jason.Attribute("Quantity").SetValue(20);
}
doc.Save(...); // save if necessary
大概是这样的:
var doc = XDocument.Load("FileName.xml");
var element = doc.Descendants("Order")
.Where(arg => arg.Attribute("Id").Value == "jason")
.Single();
element.Attribute("Quantity").Value = "3";
doc.Save("FileName.xml");
由于您创建了XML文件,因此您知道XML的根元素,因此可以使用以下代码获取所需的特定元素:
TaxonPath = XElement.Parse(xml as string);
txtSource.Text = FindGetElementValue(TaxonPath, TaxonPathElement.Source);
XElement FindGetElementValue(XElement tree,String elementname)
{
return tree.Descendants(elementName).FirstOrDefault();
}
有了这个,你可以得到元素,检查它的值,然后根据你的意愿改变它。Hmm,我从来没有见过这样的事情。非常有趣的东西!谢谢@Vir,我来看看:)