C# 使用c将xml文件转换为type=“xs:hexBinary”

C# 使用c将xml文件转换为type=“xs:hexBinary”,c#,xml,hex,C#,Xml,Hex,我正在处理一个服务,我应该以字节[]的形式提交一个xml文件。我将xmldocument.outerxml转换为byte[],还尝试了一些其他byte[]转换方法,但都没有成功。现在我正在尝试将xmldocument.outerxml转换为type=xs:hexBinary。有人能帮我吗 提前感谢。xs:hexBinary只是字节的十六进制值。以下是你可以做到的: // Load up some xml string xml = "<root><child>value&l

我正在处理一个服务,我应该以字节[]的形式提交一个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的引用


对不起,Mike Hixson先生,它对我不起作用,引发相同的异常,不是zip文件。您知道其他方法或想法吗。Mike Hixson先生,这里的字符串生成器是字符串格式的。我必须以字节的形式传递参数,如果我再次将这个字符串转换为字节,这是否是生成十六进制字节[]的正确方法。我想我不确定你们想做什么。您在原来的帖子中没有提到任何关于zip文件的内容。对不起,Mike先生,服务需要xml zip文件,因为byte[]更新了代码以显示如何获取zip压缩xml文件的字节。
// 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);