Consecutive XML serialization causes - Token StartElement in state EndRootElement would result in an invalid XML document

前端 未结 1 1300
一向
一向 2021-01-23 09:40

I am writing to the file XML serialization of the object, generated by validator.MatchPossiblyValid(string input)method. First call, serializes and write to the fil

1条回答
  •  囚心锁ツ
    2021-01-23 10:28

    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.

    0 讨论(0)
提交回复
热议问题