XPathNavigator.SetValue抛出NotSupportedException

时间:2009-10-21 15:48:06

标签: c# .net xml visual-studio-2005 xpath

我有以下代码,其最后一行在每次执行时都会导致NotSupportedException,而我还没有找到解决方法。这个假设的类似代码找到一个具有特定标题的“书”,目的是将其更新为新标题。它确实找到了正确的节点,但无法更新它。

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

node.SetValue( "NewTitle" );

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:15)

XPathNavigator个对象创建的

XPathDocument个对象是只读的(参见MSDN: Remarks
应该使用XmlDocument创建它以进行编辑:

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

node.SetValue("NewTitle");