xml namespace and xml literals
-
26-10-2019 - |
Question
I'm experimenting with xml literals in vb.net and there's something I don't get. Here's a small sample that illustrates the problem. I'm adding two PropertyGroup
nodes to an empty Visual Studio project. The first one is added as xml literal, the second as new XElement
:
Imports <xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
Module MyModule
Sub Main()
Dim vbproj = <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>
vbproj.Root.Add(<PropertyGroup></PropertyGroup>)
Dim xNameSpace As XNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"
vbproj.Root.Add(New XElement(xNameSpace + "PropertyGroup"))
Console.WriteLine(vbproj)
End Module
This code writes the following output:
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup xmlns="http://schemas.microsoft.com/developer/msbuild/2003"></PropertyGroup>
<PropertyGroup />
</Project>
As you can see, the first PropertyGroup
node contains a redundant xmlns declaration. Why is that, and can it be avoided?
Solution
This appears to be by design, based on reading the MSDN page for Imports Statement (XML Namespace).
The simplest way to avoid it is by using the SaveOptions.OmitDuplicateNamespaces
enumeration, which is available in .NET 4.0:
vbproj.AddAnnotation(SaveOptions.OmitDuplicateNamespaces)
If .NET 4.0 isn't an option then you might consider cleaning up the namespaces as shown in these two blog posts:
- Cleaning up your XML literal namespaces - provides an extension method to be used on each
XElement
to remove the namespace. - More on XML Namespaces in VB.... - provides an extension method that can be used on the root node and remove namespaces from children items by specifying
True
for the second parameter.