如何从字符串化XML中获取Enum值?

时间:2020-07-01 09:42:40

标签: c# .net xml vb.net

我有一个方法,该方法获取 stringized XML作为参数,并返回一个具有字符串的特定字段作为其属性的对象。这些字段与类字段映射。

到目前为止,我可以获得具有两个属性(Id,Title)但没有Enum属性的结果(processedObj)。我如何识别它并获取其当前值?

主班

email.Content = '<EmailClass><ID>210</ID><Title>Urgent</Title><Date>2020-06-01</Date> 
              <Action>Delete</Action></EmailClass>'

Dim processedObj = XmlProcessor.ObjectfromStrXml(Of EmailClass)(email.Content)

EmailClass类

<Serializable()>
<XmlRoot("EmailClass")>
Public Class EmailClass

    Public ID As String
    Public Title As String
 
    Public Enum Action
        Send
        Delete
    End Enum

End Class

XmlProcessor类

public static T ObjectfromStrXml<T>(string p_StrXML){
            T result;
            using (MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(p_StrXML)))
            using (StreamReader stReader = new StreamReader(mStream , Encoding.UTF8))
            using (XmlReader reader = new XmlTextReader(stReader))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                result = (T)(serializer.Deserialize(reader));
                streamReader.Close();
                memoryStream.Close();
                reader.Close();
            }

            return result;
}

1 个答案:

答案 0 :(得分:1)

请尝试以下代码:

Public Class EmailClass

    Public ID As String
    Public Title As String
    Private PAction As EAction

    Public Property Action As String
        Get
            Return PAction.ToString()
        End Get
        Set(value As String)
            PAction = [Enum].Parse(GetType(EAction), value)
        End Set
    End Property


    Public Enum EAction
        Send
        Delete
    End Enum

End Class