如何替换XML文件中的文本? [英] How do I replace text in a XML file?

查看:398
本文介绍了如何替换XML文件中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序写入xml文件,然后将其读入一些文本框。我希望能够更改文本框中的文本,然后能够将xml文件更新为文本框现在所说的内容。如何删除xml文件中的文本并将其替换为文本框文本?

这里是我正在尝试的代码

I have a program that writes to a xml file and then reads it into some text boxes.I want to be able to change the text in the textboxes and then be able to update the xml file to what the textboxes say now.How do i delete the text in the xml file and replace it with the textbox text??
here is the code i am trying

 if (isChanged)
{
      XDocument doc = XDocument.Load("SavedData.xml");
      var decendants = doc.Descendants().Where(s => s.Name ==
      tb.Name).ToList();
      foreach (XElement kid in decendants)
      {
          string value = kid.Value;
          string re= value.Replace(kid.Value, tb.Text);
      }

}





我的尝试:



i尝试使用replacewith()属性,但它取代了所有内容,而不仅仅是前一个文本。



What I have tried:

i tried using the replacewith() property but it replaced everything instead of just the former text.

推荐答案

XML文件是一个文本文件,XML规范强加了一层结构。你不能只是替换文本beicase文本文件不能这样工作 - 文本文件的一部分没有插入或删除功能,你可以做的唯一改变是追加到最后,或者重写整个文件。



因此,F-ES Sitecore就位于:执行此任务的最佳方法是使用适当的方法将XML文件读入内存阅读器(并且有很多),在内存中进行更改,然后将整个XML数据写回文件。
An XML file is a text file, with a layer of "structure" imposed upon it by the XML specification. You can't just "replace text" beicase text files don't work that way - there is no "insert" or "delete" function for a part of a text file, the only changes you can make is to append to the end, or rewrite the whole file.

So F-ES Sitecore is spot on: the best way to do this task is to read the XML file into memory using an appropriate reader (and there are quite a few of them), make your changes in memory, and then write the whole XML data back to a file.


这篇关于如何替换XML文件中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆