ElektroStudios ElektroStudios - 1 year ago 74
Vb.net Question

How to avoid XmlWriter create a default "xmlns" empty attribute?

Having this kind of node (that we can find inside a .vbproj project file):

<Import Include="Microsoft.VisualBasic"/>
<Import Include="Microsoft.Win32"/>
<Import Include="Microsoft.Win32.SafeHandles"/>

I declared a property in my class with a getter and a setter, to get a collection of the imports, or to replace the entire node content given a collection.

Well, the problem I have is that when I'm trying to replace the node content, my
instance adds an additional and empty
attribute, see this resulting example:

<Import Include="Microsoft.VisualBasic" xmlns="" />
<Import Include="Microsoft.Win32" xmlns="" />
<Import Include="Microsoft.Win32.SafeHandles" xmlns="" />

Why happens that, and how to avoid it?.

I'm open to non-efficient solutions like a string replace (only on that node), however I tried it without success.

This is the relevant code I'm using:

Public Property ImportedNamespaces As SortedSet(Of String)
Return New SortedSet(Of String)((From el As XElement In Me.ItemGroups()(1).Elements()
Select el.@Include))
End Get
Set(ByVal value As SortedSet(Of String))

Dim writer As XmlWriter = Me.ItemGroups()(1).CreateWriter
For Each s As String In value
With writer
.WriteStartElement(Nothing, "Import", Nothing)
.WriteAttributeString(Nothing, "Include", Nothing, s)
End With

' This doesn't works.
' For Each el As XElement In Me.ItemGroups()(1).Elements("Import")
' el.Attribute("xmlns").Remove()
' Next

End Set
End Property


Assuming you have an XElement then you can either use .WriteStartElement(Nothing, "Import", Me.ItemGroups()(1).Name.NamespaceName) or you might want to replace the whole XmlWriter use by

Me.ItemGroups()(1).Add(From s As String In value Select New XElement(Me.ItemGroups()(1).Name.Namespace + "Import", New XAttribute("Include", s)))