Cleaning up your XML literal namespaces
Posted
Sat, Nov 24 2007 15:16
by
bill
If you use XML literals in your code, adding one to another:
Dim e1 = <a:books></a:books>
dim e2 = <a:book></a:book>
e1.Add(e2)
You will have the xmlns declaration repeated in each of the elements, when really it is only needed once per the document or outer element. The problem is caused by VB adding a xmlns declaration as an attribute to the root element. It can get a bit more complex if you have duplicate namespace declarations with different prefixes. So I decided to write a CleanUpNS extension, that keeps the xml written clean by removing un-necessary namespace declarations. To use it, simply add a call to CleanUpNS to the end of your literals, e.g:
Dim e1 = <a:books></a:books>.CleanUpNS
dim e2 = <a:book></a:book>.CleanUpNS
e1.Add(e2)
<Runtime.CompilerServices.Extension()> _
Function CleanUpNS(ByVal el As XElement) As XElement
Dim current = el.LastAttribute
Do While current IsNot Nothing
Dim temp = current.PreviousAttribute
If current.IsNamespaceDeclaration AndAlso el.Name.NamespaceName = current.Value Then
current.Remove()
End If
current = temp
Loop
Return el
End Function
I go into more details about how this works and how the XML is stored and emitted in my January On VB article in Visual Studio Magazine.