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?
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:If .NET 4.0 isn't an option then you might consider cleaning up the namespaces as shown in these two blog posts:
XElement
to remove the namespace.True
for the second parameter.