βӔḺ*_*ⱫŌŔ 10 .net c# xml linq linq-to-xml
我有以下代码,它创建一个包含大量订单信息的XML文件.我希望能够更新此XML文件中的条目,而不是删除所有内容并重新添加所有内容.
我知道我可以这样做:
xElement.Attribute(attribute).Value = value;
Run Code Online (Sandbox Code Playgroud)
但是这将改变与属性保持同名的每个属性.例如,当条目的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");
Run Code Online (Sandbox Code Playgroud)
这是我的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>
Run Code Online (Sandbox Code Playgroud)
像这样的东西:
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");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11303 次 |
| 最近记录: |