Search code examples
c#.netxmlvisual-studio-2005xpath

XPathNavigator.SetValue Throws NotSupportedException


I have the following code, whose last line results in a NotSupportedException on every execution, and I haven't found a way around it. This hypothetical analogous code finds a "book" with a specific title, with the goal of updating it to the new title. It does find the correct node, but fails to update it.

XPathDocument xpathDoc = new XPathDocument( fileName );
XPathNavigator nav = xpathDoc.CreateNavigator();
XPathNavigator node = nav.SelectSingleNode( @"//Book[Title='OldTitle']/Title" );

node.SetValue( "NewTitle" );

Any help would be greatly appreciated.


Solution

  • XPathNavigator objects created by XPathDocument objects are read-only (see MSDN: Remarks)
    It should be created with XmlDocument to be editable:

    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(fileName);
    XPathNavigator nav = xmlDoc.CreateNavigator();
    XPathNavigator node = nav.SelectSingleNode(@"//Book[Title='OldTitle']/Title");
    
    node.SetValue("NewTitle");