Check out what happens when you create another XmlWriter
from xml
:
static void Main(string[] args)
{
var sb = new StringWriter();
using (var xml = XmlWriter.Create(sb, new XmlWriterSettings() { Indent = true }))
{
xml.WriteStartElement("root");
using (var inner = XmlWriter.Create(xml))
{
Debug.WriteLine(Object.ReferenceEquals(xml, inner));
//UH OH! Returns true
inner.WriteStartElement("payload1");
// simulate ThirdPartyLibrary.Serialise(results, inner) leaving a tag open
inner.WriteStartElement("third-party-stuff");
}
xml.WriteStartElement("payload2");
}
sb.ToString().Dump();
}
See? So when you dispose of inner
, you're actually disposing of xml
, because they are the same object.
If you check MSDN: (http://msdn.microsoft.com/en-us/library/77t6e4w3.aspx)
Return Value Type:
System.Xml.XmlWriter An XmlWriter object that is
wrapped around the specified XmlWriter object.
So I assume it's using the same object.
EDIT Here, a solution you can use:
static void Main(string[] args)
{
var sb = new StringWriter();
var sb2 = new StringWriter();
using (var xml = XmlWriter.Create(sb, new XmlWriterSettings() { Indent = true }))
{
xml.WriteStartElement("root");
using (var inner = XmlWriter.Create(sb2, new XmlWriterSettings() {Indent = true , CloseOutput=true, OmitXmlDeclaration=true}))
{
inner.WriteStartElement("payload1");
inner.WriteStartElement("third-party-stuff");
}
xml.WriteRaw(sb2.ToString());
xml.WriteStartElement("payload2");
}
Debug.WriteLine(sb.ToString());
}