首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

大伙看看这个xml如何转为对象

2014-01-05 
大伙看看这个xml怎么转为对象?resultlistuser nameName.net/useruser nameNo123/useru

大伙看看这个xml怎么转为对象?


<result>
  <list>
     <user name="Name">.net</user>
     <user name="No">123</user>
     <user name="Married">true</user>
  </list>
  <list>
     <user name="Name">ruby</user>
     <user name="No">123</user>
     <user name="Married">false</user>
  </list>
</result>


这个XML怎么转为.NET 对象?
[解决办法]

string xml = @"<result>
  <list>
     <user name=""Name"">.net</user>
     <user name=""No"">123</user>
     <user name=""Married"">true</user>
  </list>
  <list>
     <user name=""Name"">ruby</user>
     <user name=""No"">123</user>
     <user name=""Married"">false</user>
  </list>
</result>";
            ResultModel result = XmlUtil.ReadFromXml<ResultModel>(xml);


public static T ReadFromXml<T>(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return default(T);
            }

            XmlSerializer serializer = new XmlSerializer(typeof(T));
            XmlSerializerNamespaces nameSpaces = new XmlSerializerNamespaces();
            nameSpaces.Add("", "");

            object ext = null;
            try
            {
                using (TextReader reader = new StringReader(xml))
                {
                    ext = serializer.Deserialize(reader);
                    reader.Close();
                }
            }
            catch
            {
                ext = null;
            }
            return (T)ext;
        }


[XmlRoot("result")]
    public class ResultModel
    {
        [XmlElement("list")]
        public List<UserCollectionModel> List
        {
            get;
            set;
        }
    }

    public class UserCollectionModel
    {
        [XmlElement("user")]
        public List<UserModel> User
        {


            get;
            set;
        }
    }

    public class UserModel
    {
        [XmlAttribute("name")]
        public string Name
        {
            get;
            set;
        }

        [XmlText]
        public string Text
        {
            get;
            set;
        }
    }

热点排行