Wednesday 26 March 2008

Cannot set a value on node type 'Element'

This error occurs if you wrongly use the Value property of XmlNode to change the value of an element.
XmlDocument xdoc = new XmlDocument();
xdoc.Load( MapPath( "XmlSample.xml" ) );
XmlNode node =
xdoc.SelectSingleNode( "//element[@id=100]" );

// The following line will lead to
// an InvalidOperationException
node.Value = "New value!!";

xdoc.Save( MapPath( "XmlSample.xml" ) );

Instead, use the InnerText property:
node.InnerText = "New value!!";

[Edited: 4 Aug 2008]

7 comments:

Unknown said...

Thank you for documenting this issue and its fix!

Neil said...

Thanks for your comment, Mike.

Karl Söderlund said...
This comment has been removed by the author.
The_Champ said...

Thanks for the post. That helped me quickly fix the issue.

Keyur Parikh said...

Thanks it helps me too

Keyur Parikh said...

Thanks it helps me too.

Rama Charan said...

Thanks it helped me