0

It is complicating me convert an XML to an object in C#.

I want to convert an XML consisting of a list of objects 'Regla' with a series of fields (idRegla, DateFrom, DateTo, and a list of exceptions that may not appear).

I'm going crazy, I do not think it's that hard ...

Here is the XML:

<ListaReglas>
  <REGLA>
    <idRegla>2</idRegla>
    <DateFrom>2013-12-01T00:00:00</DateFrom>
    <DateTo>2015-07-25T00:00:00</DateTo>
    <Excepciones>
      <FECHA>2013-12-25T00:00:00</FECHA>
    </Excepciones>
  </REGLA>
  <REGLA>
    <idRegla>4</idRegla>
    <DateFrom>2013-12-01T00:00:00</DateFrom>
    <DateTo>2015-07-25T00:00:00</DateTo>
    <Excepciones>
      <FECHA>2013-12-25T00:00:00</FECHA>
    </Excepciones>
  </REGLA>
  <REGLA>
    <idRegla>5</idRegla>
    <DateFrom>2013-12-01T00:00:00</DateFrom>
    <DateTo>2015-07-25T00:00:00</DateTo>
    <Excepciones>
      <FECHA>2013-12-25T00:00:00</FECHA>
    </Excepciones>
  </REGLA>
  <REGLA>
    <idRegla>7</idRegla>
    <DateFrom>2013-11-19T00:00:00</DateFrom>
    <DateTo>2015-12-19T00:00:00</DateTo>
  </REGLA>
</ListaReglas>

Here is my class:

        [Serializable]
        [XmlTypeAttribute(AnonymousType = true)]
        public class ReglaRangoResult
        {
            [XmlElement(ElementName = "idRegla", IsNullable = false)]
            public int idRegla { get; set; }

            [XmlElement(ElementName = "DateFrom", IsNullable = false)]
            public DateTime DateFrom { get; set; }

            [XmlElement(ElementName = "DateTo", IsNullable = false)]
            public DateTime DateTo { get; set; }

            [XmlElement(ElementName = "Excepciones", IsNullable = true)]
            public List<DateTime> Excepciones { get; set; }

            [XmlIgnore]
            public int Peso { get; set; }
        }

And this is my code:

       [...]
       List<ReglaRangoResult> listaReglas = new List<ReglaRangoResult>();
       XmlDoc xmlDoc = new XmlDoc(rdr.GetString(0));

       foreach (XmlNode xmlNode in xmlDoc.SelectNodes("//ListaReglas/REGLA"))
       {
            listaReglas.Add(XmlToObject<ReglaRangoResult>(xmlNode.OuterXml));
       }
       [...]


        public static T XmlToObject<T>(string xml)
        {
            using (var xmlStream = new StringReader(xml))
            {
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(XmlReader.Create(xmlStream));
            }
        }

I don't understand what I'm doing wrong. Is the ReglaRangoResult misconfigured class? What is missing? What is left?

EXCEPTION RETURNED:

'Error reflecting type 'dllReglasNegocioMP.ReglaRangoResult'

4
  • Try the opposite way and examine the produced XML and compare it to your source XML. I do it this way very often to find the cause. Providing some exceptions in your question would also help others to understand the situation Commented Mar 14, 2014 at 9:59
  • What is going wrong? Any exceptions? Commented Mar 14, 2014 at 10:00
  • This is the exception returned: Error reflecting type 'dllReglasNegocioMP.ReglaRangoResult'. As you will see is not very specific Commented Mar 14, 2014 at 10:25
  • Any inner exception(s)? Commented Mar 14, 2014 at 11:35

3 Answers 3

1

In Visual Studio 2013 you can take the XML and select "Edit / Paste special / Paste XML as Classes". When you have done that you can use use XmlSerializer to serialize and deserialize in an easy way.

 var serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyPastedClass));
 MyPastedClass obj;
 using (var xmlStream = new StringReader(str))
 {
      obj = (MyPastedClass)serializer.Deserialize(xmlStream);
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, I completely unknown this functionality (I have VS 2012). Very useful.
you should dispose the StringReader, and that's why it is better to use the using for that manner
0

Take my class listed bellow. You can serilialize your object to real XML and compare it.

using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace VmsSendUtil
{
    /// <summary> Serializes and Deserializes any object to and from string </summary>
    public static class StringSerializer
    {
        ///<summary> Serializes object to string </summary>
        ///<param name="obj"> Object to serialize </param>
        ///<returns> Xml string with serialized object </returns>
        public static string Serialize<T>(T obj)
        {
            Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));

            var stringSerializer = new StringSerializer<T>();
            return stringSerializer.Serialize(obj);
        }

        /// <summary> Deserializes object from string. </summary>
        /// <param name="xml"> String with serialization XML data </param>
        public static T Deserialize<T>(string xml)
        {
            Contract.Requires(!string.IsNullOrEmpty(xml));
            Contract.Ensures(!Equals(Contract.Result<T>(), null));

            var stringSerializer = new StringSerializer<T>();
            return stringSerializer.Deserialize(xml);
        }
    }

    /// <summary> Serializes and Deserializes any object to and from string </summary>
    public class StringSerializer<T>
    {
        [ContractInvariantMethod]
        private void ObjectInvariant()
        {
            Contract.Invariant(_serializer != null);
        }

        private readonly XmlSerializer _serializer = new XmlSerializer(typeof(T));

        ///<summary> Serializes object to string </summary>
        ///<param name="obj"> Object to serialize </param>
        ///<returns> Xml string with serialized object </returns>
        public string Serialize(T obj)
        {
            Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));

            var sb = new StringBuilder();
            using (var sw = new StringWriter(sb, CultureInfo.InvariantCulture))
            {
                var tw = new XmlTextWriter(sw) { Formatting = Formatting.Indented };
                _serializer.Serialize(tw, obj);
            }
            string result = sb.ToString();
            Contract.Assume(!string.IsNullOrEmpty(result));
            return result;
        }

        /// <summary> Deserializes object from string. </summary>
        /// <param name="xml"> String with serialization XML data </param>
        public T Deserialize(string xml)
        {
            Contract.Requires(!string.IsNullOrEmpty(xml));
            Contract.Ensures(!Equals(Contract.Result<T>(), null));

            using (var stringReader = new StringReader(xml))
            {
                // Switch off CheckCharacters to deserialize special characters
                var xmlReaderSettings = new XmlReaderSettings { CheckCharacters = false };

                var xmlReader = XmlReader.Create(stringReader, xmlReaderSettings);
                var result = (T)_serializer.Deserialize(xmlReader);
                Contract.Assume(!Equals(result, null));
                return result;
            }
        }
    }
}

1 Comment

The function of your class also returns me the same exception: 'Error reflecting type 'dllReglasNegocioMP.ReglaRangoResult''
0

you get an exception that have an hierarchy that you do not define in your code. if you'll set the right hierarchy it will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.