Over-writing an XML attribute?

I have some XML as follows:

<?xmlversion="1.0"encoding="utf-8"?>
<eTrackerstatus="on"/>

I want to be able to overwrite the status attribute value in C#. How can I do this?
[870 byte] By [Nirbho] at [2008-1-12]
# 1
Hi,

You would need to use the XmlDocument class for overwriting the values.
Please find below the code snippet for overwriting the value of the attribute.


CODE SNIPPET

private void Form1_Load(object sender, EventArgs e)
{
string strXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><eTracker status=\"on\" />";
XmlDocument objXmlDoc = new XmlDocument();
objXmlDoc.LoadXml(strXml);
objXmlDoc.DocumentElement.Attributes["status"].Value = "off";
MessageBox.Show(objXmlDoc.DocumentElement.Attributes["status"].Value);
}


The code sample was written in VS2005 Beta2 - should work fine for .NET 1.1 as well.

Regards,
Vikram

Vikram at 2007-8-21 > top of Msdn Tech,.NET Development,XML and the .NET Framework...
# 2
Hi,

Thanks for this, but the xml file already exists on the server.. how can i read/write to it..?

Nirbho at 2007-8-21 > top of Msdn Tech,.NET Development,XML and the .NET Framework...
# 3
Hi,

A small change would do that :

CODE SNIPPET

private void Form1_Load(object sender, EventArgs e)
{
string strFilePath = @"C:\MyXml.xml";
XmlDocument objXmlDoc = new XmlDocument();
objXmlDoc.Load(strFilePath);
objXmlDoc.DocumentElement.Attributes["status"].Value = "off";
objXmlDoc.Save(strFilePath);
}

The code sample was written in VS2005 Beta2 - should work fine for .NET 1.1 as well.

Regards,
Vikram


http://dotnetupdate.blogspot.com
Vikram at 2007-8-21 > top of Msdn Tech,.NET Development,XML and the .NET Framework...

.NET Development

Site Classified