1. 程式人生 > >Xml CDATA 序列化

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;
        }
    }
}



相關推薦

Xml CDATA 序列

namespace Test { using System; using System.IO; using System.Text; using System.Xml; using System.Xml.Serialization;

C#:淺談使用XML實現序列

反序 student stat 類型 接口 ML tst In ise 序列化是將一個對象轉換成字節流以達到將其長期保存在內存、數據庫或文件中的處理過程。它的主要目的是保存對象的狀態以便以後需要的時候使用。與其相反的過程叫做反序列化。 序列化一個對象為了序列化一個對象,我們

C# XML序列序列舉例:XmlSerializer(轉)

1 using System; 2 using System.IO; 3 using System.Xml.Serialization; 4 5 namespace XStream 6 { 7 /// <summary> 8

C#XML序列和反序列

 最近負責的專案,用到了xml的序列化和反序列化,在此做個記錄以供下次學習使用  前言: 序列化和反序列化就是解析和反解析 序列化:將物件的狀態資訊轉換為可以儲存或傳輸的形式的過程(簡單來說就是將物件轉化為位元組過程) 反序列化:將位元組序列轉化為物件的過程

Python_基礎_(模組,time,random,os,sys,json,shelve,xml序列序列)

一,Import的基本用法 import 1.執行對應的檔案 2.引入變數名 3.當一個檔案被import,索貝import中的程式碼會被執行一遍,例如當 import cal  ##cla中有inport("xxx"),則會輸出   ## Import引用方法

用XmlSerializer進行xml序列的時候,程式報錯: 不應有

反序列化的時候 必須加上 名稱空間                     System.Xml.Serialization.XmlSerializer xmlser = new System.Xml.Serialization.XmlSerializer(_type,

包含名稱空間的xml序列 (1.7環境下)

需要引用1、    <!-- 1.7環境下處理帶名稱空間的xml BEGIN -->        <dependency>            <groupId>com.sun.xml.bind</groupId>     

C# 中XML序列和反序列

這是第一篇文章,原本是在新浪微博寫的,但是新浪不支援插入程式碼,在這裡再寫一遍。但是主要目的還是記錄下來,好記性不如爛筆頭。 不做過多介紹,直接貼我的東西 生成的xml檔案 <?xml version="1.0" encoding="utf-8"?> <

為什麼XML需要序列和反序列

注意:“為避免編譯錯誤,為可序列化的類添加了無引數建構函式。” MSDN的定義:序列化是將物件狀態轉換為可保持或可傳輸的形式的過程。序列化的補集是反序列化,後者將流轉換為物件。這兩個過程一起保證資料易於儲存和傳輸。 大家關心的是為什麼需要序列化,用傳統的方法也能實現這種需求嗎,它存在的價值是什麼,低層的原理

webapi “ObjectContent`1”類型未能序列內容類型“application/xml; charset=utf-8”的響應正文。

ted 分享 global format nbsp ica type .com 什麽 今天在來一發 webapi的一個知識點 相信用過webapi的對這個錯誤 已經看在眼裏 痛在心裏了把 我百度也搜了一下 看了一下 然後發現他們的解決辦法 並沒有什麽軟用

在.net中序列讀寫xml方法的總結

port 單詞 創建 padding 在一起 sys base msd 屏幕 在.net中序列化讀寫xml方法的總結 閱讀目錄 開始 最簡單的使用XML的方法 類型定義與XML結構的映射 使用 XmlElement 使用 XmlAttribute 使用 Inner

Android中XML文件的序列生成與解析

eval test director 南海 attribute trac cli found dir 首先,我把Person的實體類 package net.loonggg.test; public class Person { privat

C#反序列xml轉化為實體

class get c# sta spa bytes return doc 序列化 public static T DeserialXmlToModel<T>(string xmlDocument) { T cmdOb

XML序列

wan pos ria arc details ati class access tail 參考鏈接: http://blog.csdn.net/jjx0224/article/details/6164128 http://blog.csdn.net/wangzl1163/

.NET(C#):XML序列時派生類的處理

ali main 基類 bsp 處理 program ext serial pub .NET(C#):XML序列化時派生類的處理 針對基類的XmlSerializer序列化派生類 第一種方法是在基類添加XmlInclude特性,這樣的話基類的XmlSerializer可以

XML序列和反序列

對象 我們 讀取 list() 組成 pen for roo image 原文鏈接:http://www.cnblogs.com/Johnny_Z/archive/2012/06/23/2559408.html 在談XML序列化之前,我們先來說說序列化。 序列化名詞解釋:序

C#序列實體成XML後多了一個問號

非法字符 express 就是 錯誤 技術 system text alt ace 在調試時,程序報如下錯誤 原因是在C#序列化實體成XML後,前面多了一個問號,如圖所示: 導致該XML格式不是正確的XML格式,所以程序報錯。 解決辦法就是加入一段代碼,隱藏掉XML開頭

xml序列和反序列(一)

哈哈 正則表達式 eof AD regex lan value sys 註意 最近項目中需要調用第三方webservice,入參和出參采用xml格式,大致如下: 入參: <?xml version="1.0" encoding="utf-8"?> <

webService序列xml 以及去掉刪除<string xmlns =“http://tempuri.org/”>

        /// <summary>         /// 過車資訊查詢         /// </summary> &n

把物件序列化為xml格式和反序列

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