I am trying to add a new dependentAssembly to my Web.config file at run time. 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:assemblyBindi开发者_高级运维ng", 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 node is this
<dependentAssembly xmlns="">
<assemblyIdentity name="newone" publicKeyToken="608967" />
<bindingRedirect oldVersion="1" newVersion="2" />
</dependentAssembly>
I dont need the xmlns=""
attribute to be appended.
Is there a better way to do this?
Thanks.
The problem is because the new node you are adding is in "no namespace" while the parent is in the "urn:schemas-microsoft-com:asm.v1" namespace.
Solution:
Change:
string Node = "<dependentAssembly>" +
to:
string Node = "<dependentAssembly xmlns='urn:schemas-microsoft-com:asm.v1'>" +
I am not sure why its not working could be the XML serializer. The name space is right since the XmlNode assemblyBinding object is not null and the code I have specified is what I am doing and nothing more. It might be becasue of the GetElement method which creates XmlNode from a string and return 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 have anyway 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.
精彩评论