Replacing the inner text of an Xml node / element

First of all, it's C #. I am creating an online dashboard for a small group of colleagues at NHS. Below is an example of an XML file in which I need to change the inner text. I need to replace a specific item, for example "Workshop1". Since we have several workshops, I cannot afford to use a generic writer, because he will replace all the information in the XML document with this one of the codes below.

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

I use the switch case to select a specific workshop in which you can change the name and add the workshop URL, and using this code below will replace the entire 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 an XML document, find the "Workshop1" element and replace the inner text with text from the text field. and you can save it without replacing the entire document with a single node. Thanks for watching.

+8
c # xml winforms xmlreader xmlwriter
source share
1 answer

Using XmlDocument and XPath, you can do it

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

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

Learn more about XmlDocument on MSDN .

EDIT

To save a document, do this.

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

Hope this helps you.

+10
source share

All Articles