user1269016
user1269016

Reputation:

XML serialization and deserialization

I receive an XML file from a server, which contains many elements, and one attribute.

When Try and serialize/deserialize the xml, all the elements are serialized/deserialized properly, except for the attribute. Why does this happen?

here is the XML file:

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

and the class:

[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;
    }
}

Thanks for any help

Upvotes: 0

Views: 138

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038790

Try defining a sub class for request because type is attribute of the request and not of the root MyClass:

[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);
        }
    }
}

Upvotes: 2

Related Questions