C# 将对象序列化为XML

本文介绍了如何在C#中实现对象与XML之间的相互转换。通过具体的代码示例,展示了序列化C#对象为XML字符串及从XML字符串反序列化回C#对象的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在.Net 中 我们可以把C# 对象转化成为xml ,也可以把xml转化为 C#对象:

如下例子:

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

namespace Object2xml
{
    class Program
    {
        static void Main(string[] args)
        {
            hooyes a = new hooyes();
            a.ID = 1;
            a.Author = "hooyes";
            a.content = "www.hooyes.com";
            subcalss s=new subcalss();
            s.item="ok";
            a.sub = s;

            //将对象序列化成xml
            string xml = Serialize<hooyes>(a);
            Console.WriteLine(xml);

            //将xml反序列化成对象
            hooyes b = new hooyes();
            b=  Deserialize<hooyes>(b, xml);
            Console.WriteLine(b.content);

            Console.Read();
        }

        static string Serialize<T>(T t)
        {
            using (StringWriter sw = new StringWriter())
            {
                XmlSerializer xz = new XmlSerializer(t.GetType());
                xz.Serialize(sw, t);
                return sw.ToString();
            }
        }
         static T Deserialize<T>(T t, string s)
         {
             using (StringReader sr = new StringReader(s))
             {
                 XmlSerializer xz = new XmlSerializer(t.GetType());

                 return (T)xz.Deserialize(sr);
             }
         }
    }
    //[XmlRoot("root")]
    public class hooyes
    {
       // [XmlAttribute(AttributeName = "ID")]
        public int ID { get; set; }
        public string Author { get; set; }
        public string content { get; set; }
        public subcalss sub { get; set; }

    }
    public class subcalss
    {
        public string item { get; set; }
    }


}

转载于:https://www.cnblogs.com/hooyes/archive/2010/09/15/object2xml.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值