如何使用 XmlWriter 将 System.Xml.Linq.XElement 写入流
我有一个 XElement
实例,我希望使用 XmlWriter
类写入流。为什么?嗯,配置设置之一定义是否使用二进制 Xml。基于此设置,将创建合适的 XmlWriter
实例 - 通过 XmlWriter.Create(stream)
或 XmlDictionaryWriter.CreateBinaryWriter(stream))
。
无论如何,我正在尝试以下代码,但它使流为空:
using (var stream = new MemoryStream())
{
var xmlReader = new XDocument(xml).CreateReader();
xmlReader.MoveToContent();
var xmlWriter = GetXmlWriter(stream);
xmlWriter.WriteNode(xmlReader, true);
return stream.ToArray();
}
我已经检查过,xmlReader
在根 XML 元素的 MoveToContent
之后正确对齐。
我肯定做错了什么,但是什么?
谢谢。
I have an XElement
instance and I wish to write to a stream using XmlWriter
class. Why? Well, one of the configuration settings defines whether to use binary Xml or not. Based on this setting a suitable XmlWriter
instance is created - either by XmlWriter.Create(stream)
or 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.
I must be doing something wrong, but what?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您还没有展示 GetXmlWriter 的作用...但是您是否尝试过刷新写入器?
或者,将
XmlWriter
包装在另一个using
语句中:您可能也想对
XmlReader
执行相同的操作,尽管在本例中我不相信你特别需要。说了这么多,我并不完全确定您为什么要使用
XmlReader
。您无法找到相关的XElement
并使用XElement.WriteTo(XmlWriter)
?或者,如果您尝试复制整个文档,只需使用XDocument.WriteTo(XmlWriter)
You haven't shown what GetXmlWriter does... but have you tried just flushing the writer?
Alternatively, wrap the
XmlWriter
in anotherusing
statement: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.Having said all this, I'm not entirely sure why you're using an
XmlReader
at all. Any reason you can't just find the relevantXElement
and useXElement.WriteTo(XmlWriter)
? Or if you're trying to copy the whole document, just useXDocument.WriteTo(XmlWriter)