How to convert an XmlDocument to an array<byte>?

纵饮孤独 提交于 2019-12-17 23:32:27

问题


I constructed an XmlDocument and now I want to convert it to an array. How can this be done?

Thanks,


回答1:


Try the following:

using System.Text;
using System.Xml;

XmlDocument dom = GetDocument()
byte[] bytes = Encoding.Default.GetBytes(dom.OuterXml);

If you want to preserve the text encoding of the document, then change the Default encoding to the desired encoding, or follow Jon Skeet's suggestion.




回答2:


Write it to a MemoryStream and then call ToArray on the stream:

using System;
using System.IO;
using System.Text;
using System.Xml;

class Test
{
    static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        XmlElement root = doc.CreateElement("root");
        XmlElement element = doc.CreateElement("child");
        root.AppendChild(element);
        doc.AppendChild(root);

        MemoryStream ms = new MemoryStream();
        doc.Save(ms);
        byte[] bytes = ms.ToArray();
        Console.WriteLine(Encoding.UTF8.GetString(bytes));
    }
}

For more control over the formatting, you can create an XmlWriter from the stream and use XmlDocument.WriteTo(writer).




回答3:


Steve Guidi: Thanks! Your code was right on the money! Here's how I solved my special characters issue:

    public static byte[] ConvertToBytes(XmlDocument doc)
    {
        Encoding encoding = Encoding.UTF8;
        byte[] docAsBytes = encoding.GetBytes(doc.OuterXml);
        return docAsBytes;
    } 


来源:https://stackoverflow.com/questions/1500259/how-to-convert-an-xmldocument-to-an-arraybyte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!