2010-03-31 137 views
0

HI壓縮XML文件

我有一個500KB大小的XML文件,我需要將其發送到Web服務,所以我要壓縮此數據並將其發送到Web服務

我聽說過一些base24Encoding東西... 任何人都可以投入更多的光在這

假設如果我使用GZipStream如何我提前將文件發送到web服務

感謝

回答

1

像下面的東西(第一部分只是寫一些隨機xml供我們使用)。您的Web服務理想情況下會採用byte []參數,並且(如果使用基於http的WSE3或MCF)啓用MTOM,這會減少base-64開銷。您只需發佈byte[],然後在另一端反轉壓縮。

if (File.Exists("my.xml")) File.Delete("my.xml"); 
    using (XmlWriter xmlFile = XmlWriter.Create("my.xml")) { 
     Random rand = new Random(); 
     xmlFile.WriteStartElement("xml"); 
     for (int i = 0; i < 1000; i++) { 
      xmlFile.WriteElementString("add", rand.Next().ToString()); 
     } 
     xmlFile.WriteEndElement(); 
     xmlFile.Close(); 
    } 
    // now we have some xml! 
    using (MemoryStream ms = new MemoryStream()) { 
     int origBytes = 0; 
     using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) 
     using (FileStream file = File.OpenRead("my.xml")) { 
      byte[] buffer = new byte[2048]; 
      int bytes; 
      while ((bytes = file.Read(buffer, 0, buffer.Length)) > 0) { 
       zip.Write(buffer, 0, bytes); 
       origBytes += bytes; 
      } 
     } 
     byte[] blob = ms.ToArray(); 
     string asBase64 = Convert.ToBase64String(blob); 
     Console.WriteLine("Original: " + origBytes); 
     Console.WriteLine("Raw: " + blob.Length); 
     Console.WriteLine("Base64: " + asBase64.Length); 
    } 

或者,考慮不同的序列化格式;有密集的二進制協議要小得多(因此不能從gzip等中受益)。例如,通過protobuf-net序列化會給你一個非常有效的大小。但是這隻適用於對象模型,而不適用於任意的xml數據。

+0

謝謝Gravell ...我可以有反向壓縮代碼以及請? – Sathish 2010-03-31 09:39:01

+0

因爲我對使用框架2.0的Dotnet很新穎......你能爲此建議一個最佳方法 xml是從數據集中生成的,而數據集的源將是一個excel文件(使用OLEDB讀取) – Sathish 2010-03-31 09:43:57

+0

@ (GZipStream unzip = new GZipStream(incoming,CompressionMode.Decompress)) { //全部讀取... }使用(MemoryStream incoming = new MemoryStream(blob))以非常相似的方式解壓縮Sathish - – 2010-03-31 11:55:16

0

處理這種情況將讓您的網絡服務接受一個byte []參數,將代表壓縮的最佳方式XML。 Base64編碼將自動完成。要提高壓縮率,您可以使用MTOM encoding。這將避免Base64步驟,該步驟包括將字節數組轉換爲字符串,以便通過電線發送,並且可能會以壓縮比鬆動。

0

,可以有以下可供選擇:

  1. 的BinaryFormatter

    ArrayList的itemsToSerialize =新的ArrayList();

    itemsToSerialize.Add(「john」); itemsToSerialize.Add(「smith」);

    Stream stream = new FileStream(@「MyApplicationData.dat」,System.IO.FileMode.Create); 012orIFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream,itemsToSerialize);

    stream.Close();

  2. 你可以使用WCF NetTcpBinding的

  3. 你可以使用* HttpBinding對於託管在IIS WCF服務,並按照this blog這將引導您完成通過IIS建立WCF gzip壓縮

  4. 你可以壓縮響應和請求並解壓縮它

    新的StreamReader(新的GZipStream(webResponse.GetResponseStream(),CompressionMode.Decompress));

+0

BinaryFormatter的通常是Web服務非常糟糕的選擇 – 2010-03-31 09:35:51

+0

感謝Andrejev 我想去3選項...你可以請幫我與示例代碼 – Sathish 2010-03-31 09:54:03

+0

我希望你會選擇3,因爲我覺得這是最正確的事情。 – 2010-03-31 13:41:40