C# 如何将 XmlDocument 转换为数组<byte>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1500259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert an XmlDocument to an array<byte>?
提问by Newbie
I constructed an XmlDocumentand now I want to convert it to an array. How can this be done?
我构建了一个XmlDocument,现在我想将它转换为一个数组。如何才能做到这一点?
Thanks,
谢谢,
采纳答案by Steve Guidi
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.
如果要保留文档的文本编码,则将Default
编码更改为所需的编码,或者遵循Jon Skeet 的建议。
回答by Jon Skeet
Write it to a MemoryStream
and then call ToArray
on the stream:
将其写入 aMemoryStream
然后调用ToArray
流:
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)
.
为了更好地控制格式,您可以XmlWriter
从流创建一个并使用XmlDocument.WriteTo(writer)
.
回答by Daniel
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;
}