【发布时间】:2011-08-28 13:20:51
【问题描述】:
我有以下代码,它创建一个包含一堆订单信息的 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>
【问题讨论】:
标签: c# .net xml linq linq-to-xml