开发者

How to write System.Xml.Linq.XElement using XmlWriter to a stream

开发者 https://www.devze.com 2022-12-13 16:42 出处:网络
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 suitab

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.CreateBinaryWr开发者_Go百科iter(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.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消