反序列化的空间分隔字符串转换为泛型列表 [英] Deserializing a space delimited string into a Generic List

查看:105
本文介绍了反序列化的空间分隔字符串转换为泛型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样元素的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

这篇关于反序列化的空间分隔字符串转换为泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆