C# 替换 Xml 节点/元素的内部文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9174402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:15:33  来源:igfitidea点击:

Replacing the innertext of an Xml node/element

c#xmlwinformsxmlreaderxmlwriter

提问by Marshal

First of all this is C#. I am creating a internet dashboard for a small group of colleages in the NHS. Below is an example xml file in which I need to change the innertext of. I need to replace a specific element for example "Workshop1." Because we have a few workshops I cannot afford to use a general writer because it will replace all the information on the XML document with this one bit of code below.

首先这是C#。我正在为 NHS 的一小群大学创建一个互联网仪表板。下面是一个示例 xml 文件,我需要在其中更改内部文本。我需要替换特定元素,例如“Workshop1”。因为我们有一些研讨会,所以我不能使用一般的编写器,因为它将用下面的这一位代码替换 XML 文档上的所有信息。

<?xml version="1.0" ?> 
   <buttons>
      <workshop1>hello</workshop1> 
      <url1>www.google.co.uk</url1> 

I am using a switch case to select a specific workshop where you can change the name and add a URL of the workshop and using this code below will replace the whole document.

我正在使用 switch case 来选择一个特定的研讨会,您可以在其中更改名称并添加研讨会的 URL,使用下面的此代码将替换整个文档。

public void XMLW()
    {
        XmlTextReader reader = new XmlTextReader("C:\myXmFile.xml");
        XmlDocument doc = new XmlDocument(); 

        switch (comboBox1.Text)

        {
            case "button1":


                doc.Load(reader); //Assuming reader is your XmlReader 
                doc.SelectSingleNode("buttons/workshop1").InnerText = textBox1.Text;
                reader.Close();
                doc.Save(@"C:\myXmFile.xml");
                break;


        }


    }

So just to clarify I want my C# program to search through the XML document find the element "Workshop1" and replace the innertext with text from a textBox. and be able to save it without replacing the whole document with one node. Thanks for looking.

所以只是为了澄清我希望我的 C# 程序搜索 XML 文档,找到元素“Workshop1”并用 textBox 中的文本替换内部文本。并且能够保存它而无需用一个节点替换整个文档。谢谢你看。

采纳答案by Amar Palsapure

Using XmlDocumentand XPath you can do this

使用XmlDocument和 XPath 你可以做到这一点

XmlDocument doc = new XmlDocument();
doc.Load(reader); //Assuming reader is your XmlReader
doc.SelectSingleNode("buttons/workshop1").InnerText = "new text";

You can use doc.Saveto save the file also.

您也可以使用doc.Save来保存文件。

Read more about XmlDocumenton MSDN.

XmlDocumentMSDN上阅读更多信息。

EDIT

编辑

To save the document do this

要保存文档,请执行此操作

doc.Save(@"C:\myXmFile.xml"); //This will save the changes to the file.

Hope this helps you.

希望这对你有帮助。