You are trying to use a single XmlWriter
to create an XML file with multiple root elements. However, the XML standard requires exactly one root element per XML document. Your XmlWriter
is throwing the exception to indicate that the XML being created is invalid. (MCVE here.)
If you really need to concatenate two XML documents into a single file, you could use separate XmlWriters
created with XmlWriterSettings.CloseOutput
set to false
:
using (var stream = new System.IO.StreamWriter(args[1], true))
{
var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
//settings.Indent = true;
settings.CloseOutput = false;
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, validator.MatchPossiblyValid("STRING FOR PARSING"), emptyNS);
}
stream.Write(Environment.NewLine);
stream.Flush();
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, validator.MatchPossiblyValid("STRING FOR PARSING"), emptyNS);
}
//Line below throws the exception
stream.Write(Environment.NewLine);
stream.Flush();
}
Sample fiddle.
Or, better yet, don't do this at all, since an "XML Document" with multiple roots is, as stated above, not valid. Instead, serialize both objects inside some container element.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…