【发布时间】:2014-09-02 19:40:10
【问题描述】:
我正在开发一项服务,我应该将 xml 文件作为字节 [] 提交。我将 xmldocument.outerxml 转换为 byte[],我还尝试了其他一些 byte[] 转换方法,但没有成功。现在我试图将 xmldocument.outerxml 转换为 type="xs:hexBinary"。谁能帮帮我
提前致谢。
【问题讨论】:
我正在开发一项服务,我应该将 xml 文件作为字节 [] 提交。我将 xmldocument.outerxml 转换为 byte[],我还尝试了其他一些 byte[] 转换方法,但没有成功。现在我试图将 xmldocument.outerxml 转换为 type="xs:hexBinary"。谁能帮帮我
提前致谢。
【问题讨论】:
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);
更新
发现您需要压缩 Xml 后...要获得 zip 功能,您需要添加对 System.IO.Compression.FileSystem.dll 和 System.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);
【讨论】: