user3112115
user3112115

Reputation: 715

c# XMLSerializer returns null

private ResultReferences<T> GetList<T>(string result) where T : class
{
    TextReader reader = new StringReader(result);
    XmlSerializer serializer = new XmlSerializer(typeof(ResultReferences<T>));
    ResultReferences<T> response = (ResultReferences<T>)serializer.Deserialize(reader);
    return response;
}

this is the function that parses the string xml:

and this is my xml string:

<?xml version="1.0" encoding="UTF-8"?>
<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/some-api/ getCurrencyRate.xsd">
    <rates date="2015-07-07">
        <item cur1="USD" cur2="RUR">57.8215</item>
        <item cur1="EUR" cur2="RUR">63.9852</item>
        <item cur1="EUR" cur2="USD">1.1177</item>     
        <item cur1="USD" cur2="EUR">0.9037</item>
    </rates>
</result>

exactly in the line:

        ResultReferences<T> response = (ResultReferences<T>)serializer.Deserialize(reader);

returns null, why is that? is my xml wrong?

Here is the serialized code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace mynamespace
{
    [XmlType(TypeName = "currency")]
    public class oCurrency
    {
        [XmlAttribute]
        public long id { get; set; }
        [XmlAttribute]
        public string name { get; set; }
    }
}

Upvotes: 2

Views: 1610

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180808

This is the C# code that corresponds to the XML you posted:

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
    [XmlRoot(ElementName="item")]
    public class Item {
        [XmlAttribute(AttributeName="cur1")]
        public string Cur1 { get; set; }
        [XmlAttribute(AttributeName="cur2")]
        public string Cur2 { get; set; }
        [XmlText]
        public string Text { get; set; }
    }

    [XmlRoot(ElementName="rates")]
    public class Rates {
        [XmlElement(ElementName="item")]
        public List<Item> Item { get; set; }
        [XmlAttribute(AttributeName="date")]
        public string Date { get; set; }
    }

    [XmlRoot(ElementName="result")]
    public class Result {
        [XmlElement(ElementName="rates")]
        public Rates Rates { get; set; }
        [XmlAttribute(AttributeName="xsi", Namespace="http://www.w3.org/2000/xmlns/")]
        public string Xsi { get; set; }
        [XmlAttribute(AttributeName="schemaLocation", Namespace="http://www.w3.org/2001/XMLSchema-instance")]
        public string SchemaLocation { get; set; }
    }
}

It's generated, of course; that's why it's so precise. Regardless, it bears little resemblance to the C# class you provided.

Upvotes: 3

Related Questions