ASP.NET MVC 2:反序列化SPROC响应

时间:2011-01-05 04:29:51

标签: c# xml-deserialization

我需要问一个普遍的问题。我没有在我面前的代码,因为我正在我的iPhone上写这个。

我有一个表示某个XML架构的Class。我有一个返回此XML的SPROC。我需要做的是将XML反序列化为此类。

XML:

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

我需要将这个XML反序列化为自定义Person类,这样我就可以遍历这个模型并在View中吐出它。我确定会涉及某种类型的演员,我只是不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

我的解决方案:

 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);

        }

    }

和班级:

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; }
    }

}

答案 1 :(得分:0)

在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
              });