【问题标题】:Deserializing an element with different xsi:style反序列化具有不同 xsi:style 的元素
【发布时间】:2017-03-06 12:41:19
【问题描述】:

我需要反序列化包含具有两种不同类型的元素的 XML 文件。
示例:

<loop xsi:type="loopDynamicLengthType">
...
<loop xsi:type="loopTerminatedType">
...

在我的源代码中,该类被定义为:

<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'.

我该如何解决?

【问题讨论】:

    标签: xml vb.net xml-deserialization


    【解决方案1】:

    标准属性xsi:type 允许XML 元素显式声明其类型。在这种情况下,元素&lt;loop&gt; 可以有两种类型,loopDynamicLengthTypeloopTerminatedType。正如here 解释的那样,XmlSerializer 使用xsi:type 信息将XML 元素映射到特定的.Net 类型。因此,您需要做的是有一个基类(可能虽然不一定是抽象的)来表示任何可能的循环类型,有两个子类,每个子类对应于两个可能的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
    

    基类上的&lt;XmlInclude&gt; 属性指定了可能遇到的一组可能的子类型。派生类上的 &lt;XmlType(String)&gt; 属性指定将显示为相应 xsi:type 属性值的名称。

    那么你的包含类型应该是这样的:

    Public Class RootObject
        <XmlElement("loop")> Public prLoop() As PosResponseLoop 
    End Class
    

    示例fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 2011-06-24
      • 2015-10-08
      相关资源
      最近更新 更多