反序列化的空间分隔字符串转换为泛型列表转换为、字符串、序列化、列表

2023-09-04 23:32:35 作者:把你归还人海

我有一个看起来像这样元素的XML文件(简称为清楚起见):

I have an xml file with elements that look like this (abbreviated for clarity):

<post id="1" tags="tag1 tag2 tag3 tag4" />

我想这个映射使用XML反序列化下面的类,但我不能找到一种方法来映射标签属性到实际的列表(串)。

I want to map this to the following class using Xml Deserialization, but I can't find a way to map the tags attribute to an actual List(Of String).

<Serializable()> _
<XmlRootAttribute("post")> _
Public Class Post
Private m_id As Integer
Private m_tags As String

<XmlAttribute("id")> _
Public Property Id() As Integer
    Get
        Return m_id
    End Get
    Set(ByVal value As Integer)
        m_id = value
    End Set
End Property

'<XmlAttribute("tags")> _
Public Property Tags() As List(Of String)
    Get
        Return m_tags
    End Get
    Set(ByVal value As List(Of String))
        m_tags = value
    End Set
End Property
End Class

有没有什么办法来替代默认反序列化?

Is there any way to override the default Deserialization?

推荐答案

我觉得最简单的办法是有一个 RawTags 获取/设置属性,它被序列化,和标签只读属性,该属性解析RawTags到名单,其中,串&GT; 但得到的串行忽略:

I think the easiest thing to do is to have a RawTags get/set property which gets serialized, and a Tags readonly property which parses the RawTags to a List<string> but gets ignored by the serializer:

<Serializable()> 
    <XmlRootAttribute("post")> 
    Public Class Post
    Private m_id As Integer
    Private m_tags As String

    <XmlAttribute("id")> 
    Public Property Id() As Integer
        Get
            Return m_id
        End Get
        Set(ByVal value As Integer)
            m_id = value
        End Set
    End Property

   <XmlAttribute("tags")> 
    Public Property RawTags() As String
        Get
            Return m_tags 
        End Get
        Set(ByVal value As String)
            m_tags = value
        End Set
    End Property

    <XmlIgnore>
    Public ReadOnly Property Tags() As List(Of String)
        Get
            Return m_tags.Split(" ").ToList()
        End Get
    End Property
    End Class