Programmatically add dependAssembly to runtime \ assemblyBinding

I am trying to add a new dependent assembly to the Web.config file at runtime. So far my current code has

XmlNamespaceManager manager = new XmlNamespaceManager (WebConfigDoc.NameTable); manager.AddNamespace("bindings", "urn:schemas-microsoft-com:asm.v1"); XmlNode root = WebConfigDoc.DocumentElement; XmlNode assemblyBinding = root.SelectSingleNode("//bindings:assemblyBinding", manager); XmlNode newAssemblyBinding = WebConfigDoc.ImportNode(GetElement(MyNewNode()), true); assemblyBinding.AppendChild(newAssemblyBinding); } private string MyNewNode() { string Node = "<dependentAssembly>" + "<assemblyIdentity name=\"newone\" "+ " publicKeyToken=\"608967\" />" + "<bindingRedirect oldVersion=\"1\" newwVersion=\"2\" />" + "</dependentAssembly>"; return Node ; } 

This works, but the result of node is this

 <dependentAssembly xmlns=""> <assemblyIdentity name="newone" publicKeyToken="608967" /> <bindingRedirect oldVersion="1" newVersion="2" /> </dependentAssembly> 

I do not need the xmlns="" attribute.

Is there a better way to do this?

Thanks.

+4
source share
2 answers

I'm not sure why its work cannot be an XML serializer. The namespace is correct because the assembly object of the XmlNode XML node is not null, and the code I specified is what I do and nothing more. This may be due to the GetElement method, which creates an XmlNode from the string and returns a new document element.

 private static XmlElement GetElement(string xml) { //convert string to xml element XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); return doc.DocumentElement; } 

I still achieved the result using XPathNavigator. My final version.

 XmlNamespaceManager manager = new XmlNamespaceManager (WebConfigDoc.NameTable); manager.AddNamespace("bindings", "urn:schemas-microsoft-com:asm.v1"); XmlNode root = WebConfigDoc.DocumentElement; XPathNavigator assemblyBinding = root.CreateNavigator(). SelectSingleNode("//bindings:assemblyBinding", manager); assemblyBinding.AppendChild(MyNewNode()); private string MyNewNode() { string Node = "<dependentAssembly>" + "<assemblyIdentity name=\"newone\" "+ " publicKeyToken=\"608967\" />" + "<bindingRedirect oldVersion=\"1\" newwVersion=\"2\" />" + "</dependentAssembly>"; return Node ; } 

Thanks for the help.

+1
source

The problem is that the new node you are adding is in "without namespace", while the parent element is in the namespace "urn: schemas-microsoft-com: asm.v1".

Decision

Edit

  string Node = "<dependentAssembly>" + 

before

  string Node = "<dependentAssembly xmlns='urn:schemas-microsoft-com:asm.v1'>" + 
+2
source

Source: https://habr.com/ru/post/1333080/


All Articles