2014-07-12 42 views
0

我正在處理一個服務,我應該以byte []的形式提交一個xml文件。我將xmldocument.outerxml轉換爲byte [],並且我還嘗試了其他一些byte []轉換方法。現在我試圖將xmldocument.outerxml轉換爲type =「xs:hexBinary」。任何人都可以幫我使用c轉換xml文件到type =「xs:hexBinary」使用c#

在此先感謝。

回答

0

xs:hexBinary只是字節的十六進制值。下面有你如何能做到這一點:

// Load up some xml 
string xml = "<root><child>value</child></root>"; 

XmlDocument doc = new XmlDocument(); 
doc.LoadXml(xml); 

// Get OuterXml as bytes 
byte[] bytes = Encoding.UTF8.GetBytes(doc.OuterXml); 

// bytes to hex values 
StringBuilder buffer = new StringBuilder(); 

foreach (byte b in bytes) 
    buffer.AppendFormat("{0:X2}", b); 

// Results 
Console.WriteLine(buffer); 

UPDATE

發現,你需要壓縮的的Xml ......爲了得到壓縮功能後,您需要將引用添加到System.IO。 Compression.FileSystem.dllSystem.IO.Compression.dll

// Load up some xml 
string xml = "<root><child>value</child></root>"; 

XmlDocument doc = new XmlDocument(); 
doc.LoadXml(xml); 


byte[] bytes; 

// Create zip 
using (MemoryStream ms = new MemoryStream()) 
{ 
    using (ZipArchive zip = new ZipArchive(ms, ZipArchiveMode.Create)) 
    { 
     // The name of the xml file inside the zip 
     var entry = zip.CreateEntry("myxml_file.xml"); 
     using (Stream stream = entry.Open()) 
     { 
      // Save the xml file into the zip 
      doc.Save(stream); 
     } 
    } 

    // Get bytes of zip file 
    bytes = ms.GetBuffer(); 
} 

// Save the file to Debug\Bin\out.zip for testing only (remove from final code) 
File.WriteAllBytes("out.zip", bytes); 

// bytes to hex values 
StringBuilder buffer = new StringBuilder(); 

foreach (byte b in bytes) 
    buffer.AppendFormat("{0:X2}", b); 

// Results 
Console.WriteLine(buffer); 
+0

對不起Mr.Mike希克森它不是爲我工作拋出同樣的異常不file.do你知道的一個zip Ÿ另一種方法或想法。 – NandaIN

+0

Mr.Mike Hixson這裏字符串生成器是字符串格式的。我必須傳遞參數作爲字節,如果我再次將此字符串轉換爲字節是產生十六進制字節[]的正確方法。 – NandaIN

+0

我想我不知道你在做什麼。您沒有在原始文章中提及有關zip文件的任何信息。 –