Reputation: 1296
I'm trying to figure out how I can go about updating my XML file. I know how to read and write, but no idea how to update an existing record.
My XML file looks like:
And I'd like to be able to change the value of an XAttribute that's already in the file.
This is how I'm writing the file:
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("");
Is it possible to do updates, or must we first remove the existing one, and then re-add it with the new values?
Upvotes: 4
Views: 1659
Reputation: 25732
Yes you can update the attribute without deleting and re-adding. Simply get the desired XAttribute
object inside the XElement and update it's Value
property and save back the XElement to a file to see the changes.
xElement.Attribute("Quantity").Value = "15";
Upvotes: 5