XPathNavigator.SetValue Throws NotSupportedException
Asked Answered
D

2

7

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.

Dragone answered 21/10, 2009 at 15:48 Comment(0)
V
19

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");
Vocalize answered 21/10, 2009 at 15:55 Comment(2)
But how can I use an XPath expression to find a node from an XMLDocument?Dragone
Never mind, it's the same CreateNavigator() method. I didn't notice that before. Awesome, thanks!Dragone
S
0
//C#    
XmlDocument editableDocument = new XmlDocument();
editableDocument.LoadXml(originalDoc.Root.ToString());
//editable XMLDocument
editableDocument.LoadXml(originalDoc.Root.ToString()); 
//XPathNavigator
XPathNavigator xpNav = editableDocument.CreateNavigator();
XPathNavigator navNode = xpNav.SelectSingleNode("//ProcurementInstrumentForm");
// conditional check for node and value
if (navNode != null && navNode.Value == "SF 26")
{
    //set to MOD SF 30
    navNode.SetValue("SF 30");
}
Sedgewinn answered 13/6 at 18:4 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Propraetor

© 2022 - 2024 — McMap. All rights reserved.