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.
Change the Value of an Attribute In the DOM, attributes are nodes. Unlike element nodes, attribute nodes have text values. The way to change the value of an attribute, is to change its text value. This can be done using the setAttribute() method or setting the nodeValue property of the attribute node.
The InnerText property represents the concatenation of all child text nodes. Setting the InnerText property replaces all child nodes with a single text node.
Everything in an XML document is a node. For example, the entire document is the document node, and every element is an element node. Root node. The topmost node of a tree. In the case of XML documents, it is always the document node, and not the top-most element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With