我有下面的代码,它创建了一个包含大量订单信息的XML文件。我希望能够更新此XML文件中的条目,而不是删除所有内容并重新添加所有内容。
我知道我能做到:
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>发布于 2011-05-19 12:13:55
如下所示:
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");发布于 2011-05-19 12:13:47
首先,您需要搜索要更新的元素。如果您找到它,请执行更新。只需记住完成后将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发布于 2011-05-19 13:00:38
由于您创建了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();
}这样,您就可以获取元素,检查它的值,并根据需要更改它。
https://stackoverflow.com/questions/6053577
复制相似问题