c# - 使用 .NET/C# 将 byte[] 转换为 XML

标签 c# xml

我将 XML 作为字节数组 (byte[]) 存储在数据库中。现在我需要从我成功完成的数据库中获取该字节数组并将其传递给 XDocument,如下所示:

public Dictionary<string, string> ReadFromByte(byte[] UserData, string toplevelnode, string firstattribute, string secondattribute)
        {
            XDocument doc = XDocument.Load(UserData);
            Dictionary<string, string> dictionary = doc.Descendants(toplevelnode).ToDictionary(x => x.Attribute(firstattribute).Value,
                                                               x => x.Attribute(secondattribute).Value);
            return dictionary;
        }

如果我将服务器上的 XML 格式的文件传递给 XDocument,此代码可以正常工作。但是,如果我传递 byte[] 数组,它就不起作用。

任何关于如何将 byte[] 数组转换回 XML 的提示将不胜感激。

谢谢。

最佳答案

  using (var stream = new MemoryStream(UserData, false))
  {
     var doc = Xdocument.Load(stream);

     ...
  }

正如 @int3 所问,我们应该知道您用于在数据库中存储文档的编码(UTF8/16 等)。

关于c# - 使用 .NET/C# 将 byte[] 转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6096196/

相关文章:

c# - 想要写入文件,但可能同时有多个写入者,需要锁定

c# - 如何设置 IConfigurationRoot 的 Mock 以返回值

c# - Json.NET更改值并保留注释

xml - 如何在 XSLT 中获取以下同级

c# - 异步任务等待

c# - 如何在 C# 中对 Money 字段进行空检查?

android - 构建错误 : Unable to find a particular resource

javascript - 使用 RegExp 从 xml 读取值

c# - 使用 LINQ 交换元素

c# - xml 错误 : Object reference not set to an instance of an object after SelectSingleNode