edit xml file using c#,getting error invalid token

2020-02-16 02:43发布

问题:

My Problem Is My XML file having Two namespace ,so i cant change text of xml in SelectingNode Method

XmlTextReader reader = new XmlTextReader("C:\\test.xml");
                    XmlDocument doc = new XmlDocument();
                    doc.Load(reader); //Assuming reader is your XmlReader
                    XmlNamespaceManager oManager = new XmlNamespaceManager(doc.NameTable);
                    oManager.AddNamespace("ns", "http://schemas.microsoft.com//sqlserver//reporting//2005/01//reportdefinition");
                    oManager.AddNamespace("rd", "http://schemas.microsoft.com//SQLServer//reporting//reportdesigner");           
                    doc.SelectSingleNode("/ns:Report/ns:buttons/ns:workshop1", oManager).InnerText = "new text";
                    reader.Close();
                    doc.Save(@"C:\\test.xml"); 

Xml File is Having More than One namespace so problem is here icant resolve it.

and my XML file is

   <?xml version="1.0"?>
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
  <buttons>
    <workshop1>Google</workshop1>
    <url1>www.google.co.uk</url1>
  </buttons>
</Report>

回答1:

As suggested by @MatthewStrawbridge in comment, the problem is the prefixes declared pointing to incorrect namespace URL. You don't need to escape forward slashes, so the prefix that point to default namespace should be declared this way :

oManager.AddNamespace("ns", "http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition");

Then your could work just fine to change value of <workshop1> element to "new text". You don't even need to declare the second prefix mapping in the code, because you don't use it.