Nodes with namespace uri:s when modifying web.config file in SharePoint

A while back I wrote a post on how to use a real web.config file when writing modifications to SharePoint. Apparently I had missed that if a node (like the one you see below) has a namespace reference you have to handle that in a special way, thanks to Rikard Uppström for pointing that out.

So, since there is reference to a namespace uri the XPath expression pointing to this node has to be a bit special (again Rikard pointed me in the right direction).

Let´s go through some of the code. First a linq expression finds all attributes that are namespace declarations and I extract some useful information into an anonymous type that I use later in the method.
A new extension method (RemoveNamespace) is used to remove that namespace attribute otherwise LinqToXml will include that namespace in all child elements, that method is shown below.
When the linq expression finds an attribute that is a namespace it will find the parent node of that attribute (which in this case is <runtime>) and we will build the path from there.
This method adds childnodes (not sections) so next we will go through all childnodes that do not have any attributes (which really is a section but we will not bother with that).
Next we construct SPWebConfigModifications from these “sections” (childnodes). The tricky part is the XPath expressions which have to be correct in order for SharePoint to find each individual node based on the first attribute on the first element.
Note that we actually use the entire concatenated “inner xml” of each of the childnodes and in this method we do not add them individually.

The last thing to notice is that we have to “remove” (only in memory) the namespace node (in this example it is <assemblyBinding>) has to be removed from the “big” config file before we continue with the “normal” parsing.