XmlSerializer使用

XmlSerializer是对xml进行序列化操作的对象。写了一个Order的序列化方法供留念。

序列化针对有get,set的属性;属性必须是public方式;对象顺序和序列化的顺序一致。

对象定义

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Artech.XmlSerializerDemos
{
    public class Order
    {
        private double _totalPrice;

        private Guid _id;
        public Guid ID
        {
            get { return _id; }
            //set;
        }

        private DateTime _date;
        public DateTime Date
        {
            //get;
            set{_date=value;}
        }

        public string Customer
        {
            get;
            set;
        }

        public string ShipAddress
        {
            get;
            set;

        }

        public Order() { }

        public Order(double totalPrice)
        {
            this._totalPrice = totalPrice;
        }
    }
}

 

序列化方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Artech.XmlSerializerDemos
{
    class Program
    {
        static void Main(string[] args)
        {
            Order order = new Order()
            {
                //ID = Guid.NewGuid(),
                Date = DateTime.Today,
                Customer = "Foo",
                ShipAddress = "airport address"
            };
            Serialize<Order>(order, @"E:\Order.xml");
        }

        static void Serialize<T>(T instance, string fileName)
        {
            using (XmlWriter writer = new XmlTextWriter(fileName, Encoding.UTF8))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(writer, instance);
            }
        }
    }
}

 

转载于:https://www.cnblogs.com/chinaagan/p/3565476.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值