尝试在没有名称空间或声明的情况下序列化 class

Attempting to serialize a class without a namespace or declaration

我一直在按照 How can I make the xmlserializer only serialize plain xml? 上的解决方案尝试仅序列化纯文本,但是我 运行 在 [=31= 上执行此操作时遇到了一些问题]边

目的是防止行<?xml version="1.0" encoding="utf-16"?>和属性xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"显示

我有一个子如下:

  Private Sub writeXMLContent()
        For Each dataItem As dataClass In dataSet            
            Dim emptyNameSpace As XmlSerializerNamespaces = New XmlSerializerNamespaces({XmlQualifiedName.Empty})
            Dim serializer As New XmlSerializer(GetType(dataClass))
            Dim settings As New XmlWriterSettings
            settings.Indent = True
            settings.OmitXmlDeclaration = True

            Using stream As New StringWriter
                Using writer = XmlWriter.Create(stream, settings)
                    serializer.Serialize(writer, serializer, emptyNameSpace)
                    'will write each line to a file here
                End Using
            End Using
        Next
    End Sub

但是我不断遇到同样的两个错误:

  1. Using writer = XmlWriter.Create(stream, settings) 使用对象类型的操作数必须实现 system.iDisposable
  2. 引发错误
  3. serializer.Serialize(writer, serializer, emptyNameSpace) 似乎不喜欢我的第二个参数,因为它需要一个对象?我不太确定我会在这里传递什么对象?
  1. XmlWriter 没有实现 IDisposable,即它没有 Using statement 可以调用的 Dispose 方法。只需不使用 Using 语句即可修复它。

    Dim writer = XmlWriter.Create(stream, settings)
    
  2. 第二个参数必须是你想要serialize的对象,即在这种情况下可能dataItem

    serializer.Serialize(writer, dataItem)
    

关于去掉命名空间和注释,解决方法如下:

Sub Test()
    Dim dataItem = New DataClass With {.Id = 5, .Name = "Test"}

    ' Serialize.
    Dim serializer As New XmlSerializer(GetType(DataClass))
    Dim sb As New StringBuilder()
    Using writer As New StringWriter(sb)
        serializer.Serialize(writer, dataItem)
    End Using

    Dim xml = RemoveNamespaces(sb.ToString())

    Console.WriteLine(xml)
End Sub

Private Function RemoveNamespaces(ByVal xml As String) As String
    Dim doc = New XmlDocument()
    doc.LoadXml(xml)

    ' This assumes that we have only a namespace attribute on the root element.
    doc.DocumentElement.Attributes.RemoveAll()

    Dim settings As New XmlWriterSettings With {.Indent = True, .OmitXmlDeclaration = True}
    Dim sb As New StringBuilder()
    Using stringWriter As New StringWriter(sb)
        Using writer = XmlWriter.Create(stringWriter, settings)
            doc.WriteTo(writer)
        End Using
    End Using
    Return sb.ToString()
End Function

正在使用这个测试class

Public Class DataClass
    Public Property Id As Integer
    Public Property Name As String
End Class