Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

c# - Replacing the innertext of an Xml node/element

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> 

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;


        }


    }

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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";

You can use doc.Save to save the file also.

Read more about XmlDocument on MSDN.

EDIT

To save the document do this

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

Hope this helps you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...