XMLDocument - > Byte [] ...如何返回XMLDocument?

jkh*_*jkh 6 c# encoding xmldocument bytearray type-conversion

我有一个XmlDocument并获取对象的字节,如下所示:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("C:\\myxml.xml");

byte[] data = Encoding.UTF8.GetBytes(xmlDocument.outerXml);
Run Code Online (Sandbox Code Playgroud)

并且数据存储在数据库中.

现在我正在读取byte []数据,并希望返回到XmlDocument对象.我怎么能这样做,因为我不能简单地将byte []放到XmlDocument中?

谢谢.

Dar*_*rov 10

您可以使用LoadXml方法:

byte[] data = ... fetch from your db
string xml = Encoding.UTF8.GetString(data);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
// TODO: do something with the resulting XmlDocument
Run Code Online (Sandbox Code Playgroud)

更新:

根据评论部分的要求,这里是如何将字节数组加载到DataTable:

byte[] data = ... fetch from your db
DataTable dt = ... fetch from somewhere or instantiate a new;
using (var stream = new MemoryStream(data))
{
    dt.ReadXml(stream);
}
Run Code Online (Sandbox Code Playgroud)