繁体   English   中英

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

[英]ASP.NET MVC 2: Deserialize SPROC Response

我需要问一个一般性的问题。 我前面没有代码,因为我正在iPhone上编写代码。

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

XML:

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

我需要将此XML反序列化为自定义Person类,以便可以遍历此Model并将其吐到View中。 我确定涉及某种类型的转换,我只是不知道该怎么做。

我的解决方案:

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

}

在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM