更新XML文件(C#/ Linq)

βӔḺ*_*ⱫŌŔ 4 .net c# xml linq winforms

我正在试图弄清楚如何更新我的XML文件.我知道如何读写,但不知道如何更新现有记录.

我的XML文件看起来像:

我希望能够更改已存在于文件中的XAttribute的值.

这就是我写文件的方式:

        XElement xElement;
        xElement = new XElement("Orders");

        XElement element = new XElement(
            "Order",
            new XAttribute("Quantity", Quantity),
            new XAttribute("Part No", PartNo),
            new XAttribute("Description", Description),
            new XAttribute("Discount", Discount),
            new XAttribute("Freight", Freight),
            new XAttribute("Unit Value", UnitValue),
            new XAttribute("Line Total", LineTotal)
            );
        xElement.Add(element);
        xElement.Save("");
Run Code Online (Sandbox Code Playgroud)

是否可以进行更新,或者我们必须首先删除现有的更新,然后使用新值重新添加它?

Teo*_*gul 5

是的,您可以更新属性而不删除和重新添加.只需XAttribute在XElement中获取所需对象并更新其Value属性,然后将XElement保存回文件以查看更改.

xElement.Attribute("Quantity").Value = "15";
Run Code Online (Sandbox Code Playgroud)