如何使用 XmlWriter 将 System.Xml.Linq.XElement 写入流

发布于 2024-08-14 03:14:49 字数 651 浏览 4 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Bonjour°[大白 2024-08-21 03:14:49

您还没有展示 GetXmlWriter 的作用...但是您是否尝试过刷新写入器?

xmlWriter.Flush();

或者,将 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();
}

您可能也想对 XmlReader 执行相同的操作,尽管在本例中我不相信你特别需要。

说了这么多,我并不完全确定您为什么要使用 XmlReader。您无法找到相关的 XElement 并使用 XElement.WriteTo(XmlWriter)?或者,如果您尝试复制整个文档,只需使用 XDocument.WriteTo(XmlWriter)

You haven't shown what GetXmlWriter does... but have you tried just flushing the writer?

xmlWriter.Flush();

Alternatively, wrap the XmlWriter in another using statement:

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.

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 relevant XElement and use XElement.WriteTo(XmlWriter)? Or if you're trying to copy the whole document, just use XDocument.WriteTo(XmlWriter)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文