ASP.NET MVC 2: Deserialize SPROC Response
I need to ask a general question. I don't have the code in front of me because I'm writing this on my iPhone.
I have a Class that represents a certain XM开发者_运维百科L schema. I have a SPROC that returns this XML. What I need to do is deserialize the XML to this Class.
XML:
<xml>
<person>
<firstName>Bob</firstName>
<lastName>Robby</lastName>
</person>
</xml>
I need to deserialize this XML into the custom Person Class so I can loop through this Model and spit it out in the View. I'm sure there's some kind of casting involved, I just don't know how to do it.
My Solution:
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);
}
}
And Class:
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; }
}
}
in linq it would be something like this
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
});
精彩评论