Convert XML to Object C #

3

I have a string , in which I keep the serialization of an object in XML format, leaving the following form:

<miObjeto>
  <id>01</id>
  <Lista>
    <elemento>1</elemento>
    <elemento>2</elemento>
    <elemento>3</elemento>
  </Lista>
</miObjeto>

Now, what I would like is to convert that string again to an instance of an object of type miObjecto . If you could help me, it would be appreciated.

Note: here is the method I use to serialize XML objects.

public static XElement ToXml(this object input, string element)
{
    if (input == null)
        return null;

    if (string.IsNullOrEmpty(element))
        element = "object";
    element = XmlConvert.EncodeName(element);
    var ret = new XElement(element);

    if (input != null)
    {
        var type = input.GetType();
        var props = type.GetProperties();

        var elements = from prop in props
                       let name = XmlConvert.EncodeName(prop.Name)
                       let val = prop.GetValue(input, null)
                       let value = prop.PropertyType.IsSimpleType()
                            ? new XElement(name, val)
                            : val.ToXml(name)
                       where value != null
                       select value;
        ret.Add(elements);
    }
    return ret;
}
    
asked by Randall Sandoval 21.02.2017 в 17:55
source

1 answer

2
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
    [XmlRoot(ElementName="Lista")]
    public class Lista {
        [XmlElement(ElementName="elemento")]
        public List<string> Elemento { get; set; }
    }

    [XmlRoot(ElementName="miObjeto")]
    public class MiObjeto {
        [XmlElement(ElementName="id")]
        public string Id { get; set; }
        [XmlElement(ElementName="Lista")]
        public Lista Lista { get; set; }
    }

}

and then

string elXML = @"<miObjeto>
  <id>01</id>
  <Lista>
    <elemento>1</elemento>
    <elemento>2</elemento>
    <elemento>3</elemento>
  </Lista>
</miObjeto>";
XmlSerializer serializer = new XmlSerializer(typeof(MiObjeto ));
using (TextReader reader = new StringReader(elXML))
{
    MiObjeto result = (MiObjeto ) serializer.Deserialize(reader);
}
    
answered by 21.02.2017 / 18:15
source