dimanche 26 juillet 2015

Convert a generic collection to a XML in C#

I want to write a generic method that returns a XML once a collection of type T is passed. I tried below code, but doesn't work as expected and getting {"Object does not match target type."} exception. Any advise on enhancing this to include element attributes is highly appreciated. Thanks

    public static XElement GetXElements<T>(IEnumerable<T> colelction) where T : class
    {
        XElement xml = new XElement(typeof(T).GetType().Name);
        foreach(var x in typeof(T).GetProperties())
        {
            var name = x.Name;
            var value = typeof(T).GetProperty(x.Name).GetValue(x);
            xml.Add(new XElement(name,value));
        }         
        return xml;
    }

For example, if I send a collection like below to above method,

        var col = new List<Employee>()
        {
            new Employee
            {
                FirstName = "John",
                Sex= "Male"
            },
            new Employee
            {
                FirstName = "Lisa",
                Sex= "Female"
            },
        };

and invoke the method as GetXElements<Employee>(col,"Employees")I am expecting to get a XML like below

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee>
     <FirstName>John</FirstName>
     <Sex>Male</Sex>
  </Employee>
  <Employee>
     <FirstName>Lisa</FirstName>
     <Sex>Female</Sex>
  </Employee>
<Employees>





Aucun commentaire:

Enregistrer un commentaire