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]


Mike Murray said...

Thank you for documenting this issue and its fix!

Neil Pullinger said...

Thanks for your comment, Mike.

Conny said...
This comment has been removed by the author.
The_Champ said...

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

COOL GUY said...

Thanks it helps me too

COOL GUY said...

Thanks it helps me too.

Rama Charan said...

Thanks it helped me