Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Thanks,

like image 554
Newbie Avatar asked Sep 30 '09 19:09

Newbie


People also ask

How to convert XML to byte array in c#?

Here is the code. // Write id byte[] intBytes = BitConverter. GetBytes((uint)id); Array.

What is XmlDocument?

The XmlDocument class is an in-memory representation of an XML document. It implements the W3C XML Document Object Model (DOM) Level 1 Core and the Core DOM Level 2. DOM stands for document object model. To read more about it, see XML Document Object Model (DOM).

How do I convert an image to a Bytearray?

Read the image using the read() method of the ImageIO class. Create a ByteArrayOutputStream object. Write the image to the ByteArrayOutputStream object created above using the write() method of the ImageIO class. Finally convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.


2 Answers

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.

like image 122
Steve Guidi Avatar answered Oct 01 '22 02:10

Steve Guidi


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).

like image 43
Jon Skeet Avatar answered Oct 01 '22 03:10

Jon Skeet