2011-05-23 114 views
2

我将XML作为字节数组(byte [])存储在数据库中。现在,我需要从我成功地在做数据库的字节数组,并通过它的XDocument类似如下:byte [] to XML with .NET/C#

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; 
     } 

如果我通过到的XDocument XML格式的服务器上的文件时,此代码工作正常。但是,如果我传递一个byte []数组,它将不起作用。

任何提示我应该如何conert byte []数组回到XML将不胜感激。

谢谢。

+1

你是如何在数据库中存储xml文档的?使用序列化还是仅使用xml内容的字节? – crypted 2011-05-23 10:54:16

+0

您应该能够将db字段值写入MemoryStream并将该流馈送到XDocument。 – faester 2011-05-23 10:57:22

+0

是的,你如何从数据库中获取XML取决于你如何在第一时间得到它。你需要告诉我们你是如何将它加入数据库的。 – 2011-05-23 10:58:42

回答

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

    ... 
    } 

正如@ INT3问,我们应该知道,你用来存储在数据库中的文档enocoding(UTF8/16等)。

+0

我已经将XML写入如下的内存流中:MemoryStream ms = new MemoryStream(); ms.Position = 0; XmlWriter writer = new XmlTextWriter(ms,Encoding.UTF8);然后将内存流读入如下的字节数组:byte [] biteArray = new byte [ms.Length]; ms.Read(biteArray,0,(int)ms.Length); – cycero 2011-05-23 11:12:58

+0

好吧,我的答案应该工作;因为数据库中的文档应该以<?xml version =“1.0”encoding =“UTF-8”?>开头,并且XDocument.Load会正确读取它。 – 2011-05-23 11:16:30

+0

如果我喜欢你,直接将流传递给XDocument,我得到“无法将流转换为字符串。”如果我喜欢以下内容:Xdocument.Load(stream).ToString(),我会得到找不到文件'c:\ Program Files \ Microsoft Visual Studio 9.0 \ Common7 \ IDE \ System.IO.MemoryStream'。 – cycero 2011-05-23 11:24:40