[英]How to write System.Xml.Linq.XElement using XmlWriter to a stream
I have an XElement
instance and I wish to write to a stream using XmlWriter
class. 我有一个
XElement
实例,我希望使用XmlWriter
类写入流。 Why? 为什么? Well, one of the configuration settings defines whether to use binary Xml or not.
好吧,其中一个配置设置定义是否使用二进制Xml。 Based on this setting a suitable
XmlWriter
instance is created - either by XmlWriter.Create(stream)
or XmlDictionaryWriter.CreateBinaryWriter(stream))
. 基于此设置,将创建一个合适的
XmlWriter
实例 - 通过XmlWriter.Create(stream)
或XmlDictionaryWriter.CreateBinaryWriter(stream))
。
Anyway, I am trying the following code, but it leaves the stream empty: 无论如何,我正在尝试以下代码,但它将流留空:
using (var stream = new MemoryStream())
{
var xmlReader = new XDocument(xml).CreateReader();
xmlReader.MoveToContent();
var xmlWriter = GetXmlWriter(stream);
xmlWriter.WriteNode(xmlReader, true);
return stream.ToArray();
}
I have checked, xmlReader
is properly aligned after MoveToContent
at the root XML element. 我已经检查过,
xmlReader
在根XML元素的MoveToContent
之后正确对齐。
I must be doing something wrong, but what? 我一定做错了什么,但是什么?
Thanks. 谢谢。
You haven't shown what GetXmlWriter does... but have you tried just flushing the writer? 你没有展示GetXmlWriter的作用......但是你试过刷新作者吗?
xmlWriter.Flush();
Alternatively, wrap the XmlWriter
in another using
statement: 或者,将
XmlWriter
包装在另一个using
语句中:
using (var stream = new MemoryStream())
{
var xmlReader = new XDocument(xml).CreateReader();
xmlReader.MoveToContent();
using (var xmlWriter = GetXmlWriter(stream))
{
xmlWriter.WriteNode(xmlReader, true);
}
return stream.ToArray();
}
You might want to do the same for the XmlReader
as well, although in this particular case I don't believe you particularly need to. 您可能也希望对
XmlReader
也这样做,尽管在这种特殊情况下我不相信您特别需要。
Having said all this, I'm not entirely sure why you're using an XmlReader
at all. 说完这一切之后,我不完全确定你为什么要使用
XmlReader
。 Any reason you can't just find the relevant XElement
and use XElement.WriteTo(XmlWriter)
? 你有什么理由不能找到相关的
XElement
并使用XElement.WriteTo(XmlWriter)
吗? Or if you're trying to copy the whole document, just use XDocument.WriteTo(XmlWriter)
或者,如果您要复制整个文档,只需使用
XDocument.WriteTo(XmlWriter)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.