I'm trying to solve a similar problem to that I described at How to check name of element with WriteEndElement
I wrote this code with an inner and outer XmlWriter. The idea is that closing the inner XmlWriter will also close any tags left hanging by the not-perfectly-reliable third party library.
var sb = new StringWriter();
using (var xml = XmlWriter.Create(sb, new XmlWriterSettings(){Indent = true}))
{
xml.WriteStartElement("root");
using (var inner = XmlWriter.Create(xml))
{
inner.WriteStartElement("payload1");
// simulate ThirdPartyLibrary.Serialise(results, inner) leaving a tag open
inner.WriteStartElement("third-party-stuff");
}
xml.WriteStartElement("payload2");
}
sb.ToString().Dump();
I expect this to produce
<root>
<payload1>
<third-party-stuff />
</payload1>
<payload2 />
</root>
But instead I get a run-time error at the line that should write <payload2>
InvalidOperationException
The Writer is closed or in error state.
Why do I get this error? I didn't expect closing the inner XmlWriter to close the outer one.