ElektroStudios
ElektroStudios

Reputation: 20464

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

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

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

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 XmlWriter instance adds an additional and empty xmlns attribute, see this resulting example:

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

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)
    Get
        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))
        Me.ItemGroups()(1).RemoveAll()

        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)
                .WriteEndElement()
            End With
        Next
        writer.Flush()
        writer.Close()

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

    End Set
End Property

Upvotes: 0

Views: 400

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167491

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)))

Upvotes: 1

Related Questions