日期:2014-05-17  浏览次数:20726 次

已知一个xml文件,如何进行反序列化到对象
有个xml文件,其中有个结构是这样的
<Center>MSC
<SubCenter>CMC</SubCenter>
</Center>
请问如何设置对象,或者说如何进行反序列化
xml 对象

------解决方案--------------------
        public static string ObjectToXml(object obj, bool toBeIndented, Type type)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            UTF8Encoding encoding = new UTF8Encoding(false);
            XmlSerializer serializer = new XmlSerializer(type);
            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, encoding);
            writer.Formatting = (toBeIndented ? Formatting.Indented : Formatting.None);
            serializer.Serialize(writer, obj);
            string xml = encoding.GetString(stream.ToArray());
            writer.Close();
            return xml;
        }

        public static object XmlToObject(string xml, Type type)
        {
            if (xml == null)
            {
                throw new ArgumentNullException("xml");
            }
            object o = null;
            XmlSerializer serializer = new XmlSerializer(type);
            StringReader strReader = new StringReader(xml);
            XmlReader reader = new XmlTextReader(strReader);
            try