VbNet · Console
Imports System
Imports System.Collections.Generic
Imports System.Collections
Imports System.IO
Imports System.Text
Imports System.Linq
Imports System.Reflection
Imports System.Xml.Serialization
Imports System.XML
' https://stackoverflow.com/questions/72856211/why-does-xmlserializer-fail-to-serialize-this-class-even-though-i-added-the-xmli
<XmlInclude(GetType(ProfileFormatNumber))>
Public Class ProfileFormat
<XmlElement(ElementName:="e1")>
Public Property Name As String = String.Empty
End Class
Public Class ProfileFormatNumber
Inherits ProfileFormat
<XmlElement(ElementName:="f1")>
Public Property Divider As Integer = 1
End Class
Public Class Serializer(Of T)
Public Shared Function Serialize(ByVal obj As T) As String
Dim xsSubmit As XmlSerializer = New XmlSerializer(GetType(T))
Using sww = New StringWriter()
Using writer As XmlTextWriter = New XmlTextWriter(sww) With {.Formatting = Formatting.Indented}
xsSubmit.Serialize(writer, obj)
Return sww.ToString() ' I would recommend moving this out of the inner Using statement to guarantee the XmlWriter is flushed and closed
End Using
End Using
End Function
End Class
Public Module Module1
Public Sub Main()
Dim profileFormat = New ProfileFormatNumber With { .Name = "my name", .Divider = 111 }
Dim xml2 = Serializer(Of ProfileFormat).Serialize(profileFormat)
Console.WriteLine(xml2)
End Sub
End Module