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

cyc*_*ero 2 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;
        }
Run Code Online (Sandbox Code Playgroud)

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

我将非常感谢任何提示我应该如何将byte []数组转换回XML.

谢谢.

Ric*_*der 5

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

     ...
  }
Run Code Online (Sandbox Code Playgroud)

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