Xml CDATA 序列化


namespace Test
{
    using System;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    using Test.Share;
    using Microshaoft;
    public class Class1
    {
        static void Main(string[] args)
        {
            ServiceBusXmlMessage message = new ServiceBusXmlMessage();
            MessageSecurityHeader security = new MessageSecurityHeader();
            security.SenderID = "sender001";
            security.Signature = "asdasdsadsa";
            security.SignTimeStamp = "asdasdsa";
            Router router = new Router();
            router.Topic = "Topic01";
            router.From = "From01";
            router.FromReferenceID = "11111111111111";
            router.To = new string[] { "to01", "to02", "to03" };
            Encoding e = Encoding.UTF8;
            e = Encoding.GetEncoding("gb2312");
            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, e);
            XmlSerializer serializer = new XmlSerializer(router.GetType());
            string xml = SerializerHelper.ObjectToXml<Router>
                                                    (
                                                        router
                                                        , writer
                                                        , serializer
                                                    );
            message.RoutersHeader = new CDATA(xml);
            message.SecurityHeader = security;
            SampleBody sampleBody = new SampleBody();
            sampleBody.TimeStamp = "sadadsad";
            sampleBody.AreaNo = "Area1";
            sampleBody.ChannelNo = "CH1";
            stream = new MemoryStream();
            writer = new XmlTextWriter(stream, e);
            serializer = new XmlSerializer(sampleBody.GetType());
            xml = SerializerHelper.ObjectToXml<SampleBody>
                                                    (
                                                        sampleBody
                                                        , writer
                                                        , serializer
                                                    );
            message.Body = new CDATA(xml);
            stream = new MemoryStream();
            writer = new XmlTextWriter(stream, e);
            serializer = new XmlSerializer(message.GetType());
            xml = SerializerHelper.ObjectToXml<ServiceBusXmlMessage>
                                                    (
                                                        message
                                                        , writer
                                                        , serializer
                                                    );
            Console.WriteLine("Xml序列化:");
            Console.WriteLine(xml);
            Console.WriteLine("Xml反序列化:");
            ServiceBusXmlMessage message2 = SerializerHelper.XmlToObject<ServiceBusXmlMessage>(xml);
            Console.WriteLine(message2.SecurityHeader.SenderID);
            Console.WriteLine("hi: " + message2.RoutersHeader.InnerSourceXml);
            Console.WriteLine("hi: " + message2.RoutersHeader.InnerXml);
            Console.WriteLine("body: " + message2.Body.OuterXml);
            Console.WriteLine("body: " + message2.Body.InnerXml);
            Router router2 = SerializerHelper.XmlToObject<Router>(message2.RoutersHeader.InnerXml);
            Console.WriteLine(router2.To[0]);
            SampleBody sampleBody2 = SerializerHelper.XmlToObject<SampleBody>(message2.Body.InnerXml);
            Console.WriteLine(sampleBody2.AreaNo);
            //Console.WriteLine("Hello World");
            //Console.WriteLine(Environment.Version.ToString());
            Console.ReadLine();
        }
    }
}
namespace Test.Share
{
    using System;
    using System.Xml;
    using System.Xml.Schema;
    using System.Xml.Serialization;
    [XmlRoot("ServiceBusXmlMessage")]
    [Serializable]
    public class ServiceBusXmlMessage
    {
        [XmlElement("Security", typeof(MessageSecurityHeader))]
        public MessageSecurityHeader SecurityHeader;
        [XmlElement("Routers", typeof(CDATA))]
        public CDATA RoutersHeader;
        [XmlElement("Body", typeof(CDATA))]
        public CDATA Body;
    }
    [Serializable]
    public class MessageSecurityHeader
    {
        [XmlAttribute("SenderID")]
        public string SenderID;
        [XmlAttribute("Signature")]
        public string Signature;
        [XmlAttribute("SignTimeStamp")]
        public string SignTimeStamp;
    }
    [Serializable]
    public class Router
    {
        [XmlAttribute("Topic")]
        public string Topic;
        [XmlAttribute("From")]
        public string From;
        [XmlAttribute("FromReferenceID")]
        public string FromReferenceID;
        [XmlElement("To", typeof(string))]
        public string[] To;
    }
    [Serializable]
    public class SampleBody
    {
        [XmlAttribute("TimeStamp")]
        public string TimeStamp;
        [XmlElement("AreaNo")]
        public string AreaNo;
        [XmlElement("ChannelNo")]
        public string ChannelNo;
    }
    public class CDATA : IXmlSerializable
    {
        public CDATA()
        {
        }
        public CDATA(string xml)
        {
            this._outerXml = xml;
        }
        private string _outerXml;
        public string OuterXml
        {
            get
            {
                return _outerXml;
            }
        }
        private string _innerXml;
        public string InnerXml
        {
            get
            {
                return _innerXml;
            }
        }
        private string _innerSourceXml;
        public string InnerSourceXml
        {
            get
            {
                return _innerXml;
            }
        }
        XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            string s = reader.ReadInnerXml();
            string startTag = "<![CDATA[";
            string endTag = "]]>";
            char[] trims = new char[] { '\r', '\n', '\t', ' ' };
            s = s.Trim(trims);
            if (s.StartsWith(startTag) && s.EndsWith(endTag))
            {
                s = s.Substring(startTag.Length, s.LastIndexOf(endTag) - startTag.Length);
            }
            this._innerSourceXml = s;
            this._innerXml = s.Trim(trims);
        }
        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            writer.WriteCData(this._outerXml);
        }
    }
}
namespace Microshaoft
{
    using System;
    using System.IO;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
    public static class SerializerHelper
    {
        public static T XmlToObject<T>(string Xml)
        {
            StringReader stringReader = new StringReader(Xml);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(xmlReader);
        }
        public static string ObjectToXml<T>
                                    (
                                        T Object
                                        , XmlTextWriter writer
                                        , XmlSerializer serializer
                                    )
        {
            serializer.Serialize(writer, Object, null);
            MemoryStream stream = writer.BaseStream as MemoryStream;
            byte[] bytes = stream.ToArray();
            Encoding e = EncodingHelper.IdentifyEncoding
                                            (
                                                bytes
                                                , Encoding.GetEncoding("gb2312")
                ///                                                , new Encoding[]
                ///                                                        {
                ///                                                            Encoding.UTF8
                ///                                                            , Encoding.Unicode
                ///                                                        }
                                            );
            byte[] buffer = e.GetPreamble();
            int offset = buffer.Length;
            buffer = new byte[bytes.Length - offset];
            Buffer.BlockCopy(bytes, offset, buffer, 0, buffer.Length);
            string s = e.GetString(buffer);
            return s;
        }
        public static string ObjectToXml<T>(T Object, Encoding e)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream())
            {
                XmlTextWriter writer = new XmlTextWriter(stream, e);
                string s = ObjectToXml<T>
                                    (
                                        Object
                                        , writer
                                        , serializer
                                    );
                writer.Close();
                writer = null;
                return s;
            }
        }
        public static byte[] ObjectToBinary<T>
                                    (
                                        T Object
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formater = new BinaryFormatter();
                formater.Serialize(stream, Object);
                byte[] buffer = stream.ToArray();
                return buffer;
            }
        }
        public static T BinaryToObject<T>
                                    (
                                        byte[] data
                                    )
        {
            using (MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formater = new BinaryFormatter();
                stream.Write(data, 0, data.Length);
                stream.Position = 0;
                T Object = (T)formater.Deserialize(stream);
                return Object;
            }
        }
    }
}
namespace Microshaoft
{
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    public static class EncodingHelper
    {
        public static Encoding IdentifyEncoding
                                    (
                                        Stream stream
                                        , Encoding defaultEncoding
                                        , Encoding[] identifyEncodings
                                    )
        {
            byte[] data = StreamDataHelper.ReadDataToBytes(stream);
            return IdentifyEncoding
                        (
                            data
                            , defaultEncoding
                            , identifyEncodings
                        );
        }
        public static Encoding IdentifyEncoding
                                    (
                                        Stream stream
                                        , Encoding defaultEncoding
                                    )
        {
            byte[] data = StreamDataHelper.ReadDataToBytes(stream);
            return IdentifyEncoding
                        (
                            data
                            , defaultEncoding
                        );
        }
        public static Encoding IdentifyEncoding
                                    (
                                        byte[] data
                                        , Encoding defaultEncoding
                                    )
        {
            EncodingInfo[] encodingInfos = Encoding.GetEncodings();
            List<Encoding> list = new List<Encoding>();
            foreach (EncodingInfo info in encodingInfos)
            {
                Encoding e = info.GetEncoding();
                if (e.GetPreamble().Length > 0)
                {
                    list.Add(e);
                    //System.Console.WriteLine(e.EncodingName);
                }
            }
            Encoding[] encodings = new Encoding[list.Count];
            list.CopyTo(encodings);
            return IdentifyEncoding
                        (
                            data
                            , defaultEncoding
                            , encodings
                        );
        }
        public static Encoding IdentifyEncoding
                                    (
                                        byte[] data
                                        , Encoding defaultEncoding
                                        , Encoding[] identifyEncodings
                                    )
        {
            Encoding encoding = defaultEncoding;
            foreach (Encoding e in identifyEncodings)
            {
                byte[] buffer = e.GetPreamble();
                int l = buffer.Length;
                if (l == 0)
                {
                    continue;
                }
                bool flag = false;
                for (int i = 0; i < l; i++)
                {
                    if (buffer[i] != data[i])
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    continue;
                }
                else
                {
                    encoding = e;
                }
            }
            return encoding;
        }
    }
}
namespace Microshaoft
{
    using System.IO;
    public static class StreamDataHelper
    {
        public static byte[] ReadDataToBytes(Stream stream)
        {
            byte[] buffer = new byte[64 * 1024];
            MemoryStream ms = new MemoryStream();
            int r = 0;
            int l = 0;
            long position = -1;
            if (stream.CanSeek)
            {
                position = stream.Position;
                stream.Position = 0;
            }
            while (true)
            {
                r = stream.Read(buffer, 0, buffer.Length);
                if (r > 0)
                {
                    l += r;
                    ms.Write(buffer, 0, r);
                }
                else
                {
                    break;
                }
            }
            byte[] bytes = new byte[l];
            ms.Position = 0;
            ms.Read(bytes, 0, (int)l);
            ms.Close();
            ms.Dispose();
            ms = null;
            if (position >= 0)
            {
                stream.Position = position;
            }
            return bytes;
        }
    }
}

posted @ 2010-11-27 02:24  于斯人也  阅读(2416)  评论(0编辑  收藏  举报