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

问题描述:

首先,这是C#。我正在为NHS中的一小群大学创建互联网仪表板。
下面是一个示例xml文件,我需要在其中更改其内部文本。我需要替换特定的元素,例如 Workshop1。因为我们有几个讲习班,所以我不能聘请一般作家,因为它将用下面的这段代码代替XML文档上的所有信息。

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.

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

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

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.

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;


        }


    }

因此,为了澄清一下,我希望我的C#程序在XML文档中进行搜索,找到元素 Workshop1,然后用来自textBox的文本替换内部文本。并且能够保存它而无需用一个节点替换整个文档。感谢您的光临。

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.

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

Using XmlDocument and XPath you can do this

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

您可以使用 doc.Save 保存

有关XmlDocument 的详细信息。 com / en-us / library / system.xml.xmldocument.aspx rel = noreferrer> MSDN 。

Read more about XmlDocument on MSDN.

编辑 >

要保存文档,请执行以下操作

To save the document do this

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

希望这对您有所帮助。