为什么即使我为派生类添加了XmlInclude属性,XmlSerializer也无法序列化此类



问题

我正在尝试对类"进行XML序列化;ProfileSerialize";但当在下面显示的Serialize函数中调用xsSubmit.Serialize(writer, obj)时,我会得到这个内部异常。

异常

消息=";不应为ProfileFormatNumber类型。使用XmlInclude或SoapInclude属性可以指定静态未知的类型">

我已经尝试过的

我尝试实现这些线程中提到的解决方案:

  1. 如何在Xml中序列化派生类
  2. 使用XmlSerializer序列化派生类

可复制示例

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:="e1")>
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

我的问题

我需要如何修改我的代码才能正确使用<XmlInclude(GetType())>属性我尝试在多个地方添加它,但总是收到相同的异常。

您的问题不在于XmlInclude。您的问题是,您试图通过在ProfileFormatNumberDivider(来自基类)Name的两个属性上设置<XmlElement(ElementName:="e1")>,将它们分配给相同的元素名称<e1>。也就是说,如果能够按原样序列化ProfileFormatNumber,XML将看起来像:

<ProfileFormat xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="ProfileFormatNumber">
<e1>my name</e1>
<e1>111</e1>
</ProfileFormat>

然而,XmlSerializer不支持这一点(可能是因为反序列化中会有歧义),因此出现了(稍微难以理解的)错误,抱怨元素名称e1已经存在:

The XML element 'e1' from namespace '' is already present in the current scope. Use XML attributes to specify another XML name or namespace for the element.]

相反,对ProfileFormatNumber.Divider使用不同的模糊元素名称,例如<f1>:

<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

在这里演示小提琴。

相关内容

  • 没有找到相关文章

最新更新