2011-05-18 74 views
4

我想弄清楚如何更新我的XML文件。我知道如何读写,但不知道如何更新现有的记录。更新XML文件(C#/ Linq)

我的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(""); 

是否有可能做更新,或者必须首先删除现有的一个,然后用新值重新添加呢?

回答

5

是的,你可以更新属性而不删除和重新添加。只需在XElement中获取所需的XAttribute对象并更新它的Value属性并将XElement保存到文件以查看更改。

xElement.Attribute("Quantity").Value = "15"; 
+0

嗯..谢谢 - 这很有道理:)我和我的老朋友智能感知会找出其他答案:P – 2011-05-18 14:48:50

+1

不客气。 – 2011-05-18 14:54:02

+0

哦...这很容易吗?真棒。感谢编辑! – 2011-05-18 15:07:07