0

我从服务器收到一个 XML 文件,其中包含许多元素和一个属性。

当尝试对 xml 进行序列化/反序列化时,所有元素都已正确序列化/反序列化,但属性除外。为什么会这样?

这是 XML 文件:

"<msg><msisdn>123456789</msisdn><sessionid>535232573</sessionid><phase>2</phase><request type=\"1\">*120*111#</request></msg>"

和班级:

[Serializable]
[XmlRoot(ElementName = "msg", Namespace = "")]
public class myClass
{
    [XmlElement(ElementName = "msisdn")]
    public string number = string.Empty;
    [XmlElement(ElementName = "sessionid")]
    public string sessionID = string.Empty;
    [XmlAttribute(AttributeName = "type")]
    public string requestType = string.Empty;
    [XmlElement(ElementName = "request")]
    public string request = string.Empty;
    [XmlElement(ElementName = "phase")]
    public string phase = string.Empty;

    public override string ToString()
    {
        return number + " - " + sessionID;
    }
}

谢谢你的帮助

4

1 回答 1

2

尝试为 request 定义一个子类,因为它是 root 的而不是 root 的type属性:requestMyClass

[XmlRoot(ElementName = "msg", Namespace = "")]
public class MyClass
{
    [XmlElement(ElementName = "msisdn")]
    public string Number { get; set; }

    [XmlElement(ElementName = "sessionid")]
    public string SessionID { get; set; }

    [XmlElement(ElementName = "request")]
    public Request Request { get; set; }

    [XmlElement(ElementName = "phase")]
    public string Phase { get; set; }

    public override string ToString()
    {
        return Number + " - " + SessionID;
    }
}

public class Request
{
    [XmlAttribute(AttributeName = "type")]
    public string Type { get; set; }

    [XmlText]
    public string Value { get; set; }
}

class Program
{
    static void Main()
    {
        var serializer = new XmlSerializer(typeof(MyClass));
        using (var stringReader = new StringReader("<msg><msisdn>123456789</msisdn><sessionid>535232573</sessionid><phase>2</phase><request type=\"1\">*120*111#</request></msg>"))
        using (var xmlReader = XmlReader.Create(stringReader))
        {
            var obj = (MyClass)serializer.Deserialize(xmlReader);
            Console.WriteLine(obj.Request.Type);
        }
    }
}
于 2012-05-15T14:58:40.953 回答