简体   繁体   中英

Overwrite specific XML node

I have a XML file of the following format:

<Alarms>
   <Alarm>
      <Id>1</Id>
      <Severity>Warning</Severity>
      <Comments></Comments>
   </Alarm>
   <Alarm>
      <Id>2</Id>
      <Severity>Error</Severity>
      <Comments>Restart the machine</Comments>
   </Alarm>
   ...

My program has a GUI which gives the user the ability to edit the Comments of an alarm. I am trying to come up with the best solution for the actions to take when a user is done editing and wants to save the changes. The XML file isn't extremely large (it does not warrant a database) but large enough that I do not want to overwrite the entire thing every time a change is made to a single alarm. Is it possible to target only a specific node and edit the Comments attribute without then having to re-write everything?

I'm looking for a XML-specific solution... I want to avoid regular flat-file methods that involve going to a specific line in a file and then editing that line. Perhaps something exists for XML files that I'm not privy to. I'm currently working with a .NET 2 project but will soon be upgrading to 4.5, so any solution works for me.

You can load up the xml in XmlDocument class. Navigate with an XPath query to the Comments node you want to edit and change the value. When you are done, just save the document to the same file name or a different one.

Here is an example using a Console Application.

// The Id of the Alarm to edit
int idToEdit = 2;

// The new comment for the Alarm
string newCommentValue = "Here is a new comment";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

XmlNode commentsElement = doc.SelectSingleNode(String.Format("Alarms/Alarm[Id = '{0}']/Comments", idToEdit));
commentsElement.InnerText = newCommentValue;

doc.Save(Console.Out);

Here is a working fiddle: https://dotnetfiddle.net/eQROet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM