反序列化具有不同 xsi:style 的元素
Deserializing an element with different xsi:style
我需要反序列化一个 XML 文件,该文件包含一个具有两种不同类型的元素。
示例:
<loop xsi:type="loopDynamicLengthType">
...
<loop xsi:type="loopTerminatedType">
...
在我的源代码中,class 定义为:
<XmlElement("loop")> Public prLoop() As PosResponseLoop
第二个定义为:
<XmlInclude(GetType(loopTerminatedType))> _
Public Class PosResponseLoop
第一个可以用类似的方式和相同的名称定义,
<XmlInclude(GetType(loopDynamicLengthType))> _
Public Class PosResponseLoop
但是编译器说:
class 'PosResponseLoop' and class 'PosResponseLoop' conflict in namespace 'WindowsApplication1'.
我该如何解决?
标准属性 xsi:type
allows an XML element to explicitly assert its type. In this case, the element <loop>
can have two types, loopDynamicLengthType
and loopTerminatedType
. As explained here、XmlSerializer
使用 xsi:type
信息将 XML 元素映射到特定的 .Net 类型。因此,您需要做的是有一个基数 class(可能但不一定是抽象的)来表示任何可能类型的循环,有两个子classes,每个对应于两个可能的 xsi:type
值:
<XmlInclude(GetType(LoopTerminatedType))> _
<XmlInclude(GetType(LoopDynamicLengthType))> _
Public MustInherit Class PosResponseLoop
End Class
<XmlType("loopTerminatedType")> _
Public Class LoopTerminatedType
Inherits PosResponseLoop
End Class
<XmlType("loopDynamicLengthType")> _
Public Class LoopDynamicLengthType
Inherits PosResponseLoop
End Class
派生的 classes 上的 <XmlInclude>
attributes on the base class specify the set of possible subtypes that might be encountered. The <XmlType(String)>
属性指定将显示为相应 xsi:type
属性值的名称。
那么您的包含类型应该如下所示:
Public Class RootObject
<XmlElement("loop")> Public prLoop() As PosResponseLoop
End Class
示例 fiddle.
我需要反序列化一个 XML 文件,该文件包含一个具有两种不同类型的元素。
示例:
<loop xsi:type="loopDynamicLengthType">
...
<loop xsi:type="loopTerminatedType">
...
在我的源代码中,class 定义为:
<XmlElement("loop")> Public prLoop() As PosResponseLoop
第二个定义为:
<XmlInclude(GetType(loopTerminatedType))> _
Public Class PosResponseLoop
第一个可以用类似的方式和相同的名称定义,
<XmlInclude(GetType(loopDynamicLengthType))> _
Public Class PosResponseLoop
但是编译器说:
class 'PosResponseLoop' and class 'PosResponseLoop' conflict in namespace 'WindowsApplication1'.
我该如何解决?
标准属性 xsi:type
allows an XML element to explicitly assert its type. In this case, the element <loop>
can have two types, loopDynamicLengthType
and loopTerminatedType
. As explained here、XmlSerializer
使用 xsi:type
信息将 XML 元素映射到特定的 .Net 类型。因此,您需要做的是有一个基数 class(可能但不一定是抽象的)来表示任何可能类型的循环,有两个子classes,每个对应于两个可能的 xsi:type
值:
<XmlInclude(GetType(LoopTerminatedType))> _
<XmlInclude(GetType(LoopDynamicLengthType))> _
Public MustInherit Class PosResponseLoop
End Class
<XmlType("loopTerminatedType")> _
Public Class LoopTerminatedType
Inherits PosResponseLoop
End Class
<XmlType("loopDynamicLengthType")> _
Public Class LoopDynamicLengthType
Inherits PosResponseLoop
End Class
派生的 classes 上的 <XmlInclude>
attributes on the base class specify the set of possible subtypes that might be encountered. The <XmlType(String)>
属性指定将显示为相应 xsi:type
属性值的名称。
那么您的包含类型应该如下所示:
Public Class RootObject
<XmlElement("loop")> Public prLoop() As PosResponseLoop
End Class
示例 fiddle.