views:

1071

answers:

1

Dear ladies and sirs.

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.

+4  A: 

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)

Jon Skeet
That's it. I did not flush the writer. Thanks.
mark
BTW, Thanks for the comment, I will change my implementation accordingly.
mark