简体   繁体   English

覆盖特定的XML节点

[英]Overwrite specific XML node

I have a XML file of the following format: 我有以下格式的XML文件:

<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. 我的程序有一个GUI,使用户可以编辑警报的Comments 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. XML文件不是很大(它不能保证有数据库),但是足够大,我不想每次对单个警报进行更改时都覆盖整个内容。 Is it possible to target only a specific node and edit the Comments attribute without then having to re-write everything? 是否可以仅将特定节点作为目标并编辑Comments属性,而不必重新编写所有内容?

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. 我正在寻找一种特定于XML的解决方案...我想避免使用常规的平面文件方法,这些方法涉及到文件中的特定行然后编辑该行。 Perhaps something exists for XML files that I'm not privy to. 也许我不了解XML文件的某些东西。 I'm currently working with a .NET 2 project but will soon be upgrading to 4.5, so any solution works for me. 我目前正在使用.NET 2项目,但很快将升级到4.5,因此任何解决方案都对我有用。

You can load up the xml in XmlDocument class. 您可以在XmlDocument类中加载xml。 Navigate with an XPath query to the Comments node you want to edit and change the value. 使用XPath查询导航到要编辑并更改值的Comments节点。 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 这是一个有效的小提琴: https : //dotnetfiddle.net/eQROet

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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