简体   繁体   中英

Converting XML into a c# object

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'

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM