Pregunta

necesito hacer una pregunta general. No tengo el código frente a mí porque yo estoy escribiendo esto en mi iPhone.

Tengo una clase que representa un cierto esquema XML. Tengo un procedimiento almacenado que devuelve este XML. Lo que necesita hacer es deserializar el XML para esta clase.

XML:

<xml>
     <person>
             <firstName>Bob</firstName>
             <lastName>Robby</lastName>
     </person>
</xml>

necesito para deserializar el XML en la costumbre persona de clase así que puede recorrer a través de este modelo y la escupió en la vista. Estoy seguro de que hay algún tipo de fundición involucrados, sólo que no sé cómo hacerlo.

¿Fue útil?

Solución

Mi Solución:

 public class Program {
        public static void Main(string[] args) {


            string xml = @"<xml><person><firstName>Bob</firstName><lastName>Robby</lastName></person></xml>";

            var doc = XElement.Parse(xml);
            var person = (from x in doc.Elements("person") select x).FirstOrDefault();

            XmlSerializer serializer = new XmlSerializer(typeof(Person));

            var sr = new StringReader(person.ToString());
            // Use the Deserialize method to restore the object's state.
            var myPerson = (Person)serializer.Deserialize(sr);

        }

    }

Y Clase:

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

namespace ConsoleApplication3 {

    [XmlRoot("person")]
    public class Person {

        [XmlElement("firstName")]
        public string FirstName { get; set; }

        [XmlElement("lastName")]
        public string LastName { get; set; }
    }

}

Otros consejos

en LINQ sería algo como esto

XDocument xmlFile = XDocument.Parse(yourXml)    
var people = (from x in xmlFile.Descendants("person")
              select new Person(){
                      firstname = (string)x.Element("firstname").Value,
                      lastname = (string)x.Element("lastname").Value
              });
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top