【问题标题】:Convert xml file to type="xs:hexBinary" using c#使用 c# 将 xml 文件转换为 type="xs:hexBinary"
【发布时间】:2014-09-02 19:40:10
【问题描述】:

我正在开发一项服务,我应该将 xml 文件作为字节 [] 提交。我将 xmldocument.outerxml 转换为 byte[],我还尝试了其他一些 byte[] 转换方法,但没有成功。现在我试图将 xmldocument.outerxml 转换为 type="xs:hexBinary"。谁能帮帮我

提前致谢。

【问题讨论】:

    标签: c# xml hex


    【解决方案1】:

    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.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);
    

    【讨论】:

    • 对不起,Mike Hixson 先生,它不适合我抛出相同的异常而不是 zip 文件。你知道任何其他方法或想法。
    • Mike Hixson 先生这里的字符串生成器是字符串格式的。如果我再次将此字符串转换为字节,我必须将参数作为字节传递是产生十六进制字节[]的正确方法吗?
    • 我想我不确定您要做什么。您在原始帖子中没有提及有关 zip 文件的任何内容。
    • 对不起,Mike 先生,该服务需要 xml zip 文件作为字节 []
    • 更新了代码以显示如何获取 zip 压缩的 xml 文件的字节。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2012-06-08
    • 2019-04-11
    • 2015-10-14
    相关资源
    最近更新 更多