C#.NET解析XML(简单实例)

首先,封装一个XML序列化和反序列化的函数。

using System.Xml.Serialization;
using System.IO;

 

    public class XmlSerialize
    {
        /// <summary>
        /// 反序列化XML为类实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xmlObj"></param>
        /// <returns></returns>
        public static T DeserializeXML<T>(string xmlObj)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StringReader reader = new StringReader(xmlObj))
            {
                return (T)serializer.Deserialize(reader);
            }
        }

        /// <summary>
        /// 序列化类实例为XML
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string SerializeXML<T>(T obj)
        {
            using (StringWriter writer = new StringWriter())
            {
                new XmlSerializer(obj.GetType()).Serialize((TextWriter)writer, obj);
                return writer.ToString();
            }
        }
    }


再建一个实体类,添加序列化标记

    [Serializable]
    public class UserInfo
    {
        public string Name;

        public string sex;
    }


OK,我们先来序列化一下

        static void Main(string[] args)
        {

            UserInfo user = new UserInfo();
            user.Name = "bdstjk";
            user.sex = "男";
            String strXml = XmlSerialize.SerializeXML<UserInfo>(user);
            Console.WriteLine(strXml);
	}


序列化结果:

<?xml version="1.0" encoding="utf-16"?>
<UserInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>bdstjk</Name>
  <sex>男</sex>
</UserInfo>


反序列化我们就用这个序列化后的XML后吧

        static void Main(string[] args)
        {
            string strXml = "<?xml version=\"1.0\" encoding=\"utf-16\"?><UserInfo xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><Name>bdstjk</Name><sex>男</sex></UserInfo>";
            UserInfo user = XmlSerialize.DeserializeXML<UserInfo>(strXml);
            Console.WriteLine(user.Name);
	}


好了。。最简单的XML序列化,反序列化已经完成。。

复杂一些的XML操作,请看:

C#.NET解析XML(使用属性控制 XML 序列化)

 

 

你可能感兴趣的:(xml,String,user,Class,encoding)