[英]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. 我前面没有代码,因为我正在iPhone上编写代码。
I have a Class that represents a certain XML schema. 我有一个表示特定XML架构的类。 I have a SPROC that returns this XML. 我有一个返回此XML的SPROC。 What I need to do is deserialize the XML to this Class. 我需要做的是将XML反序列化为此类。
XML: 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. 我需要将此XML反序列化为自定义Person类,以便可以遍历此Model并将其吐到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 在linq中会是这样的
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.