连续的XML序列化原因 - 状态EndRootElement中的Token StartElement将导致无效的XML文档

时间:2017-05-16 18:21:30

标签: c# xml serialization

我正在写入由validator.MatchPossiblyValid(string input)方法生成的对象的文件XML序列化。首先调用,序列化并写入文件。但是,第二次调用失败,但有例外:System.InvalidOperationException: 'Token StartElement in state EndRootElement would result in an invalid XML document. Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment. '

XmlSerializerNamespaces emptyNS = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var serializer = new XmlSerializer(typeof(PDPCustomerInfoInvalid));
var settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
//settings.Indent = true;
using (var stream = new System.IO.StreamWriter(args[1], true))
{
    using (var writer = XmlWriter.Create(stream, settings))
        {

                serializer.Serialize(writer, validator.MatchPossiblyValid("STRING FOR PARSING"), emptyNS);
                stream.Write(Environment.NewLine);
                stream.Flush();
                //Line below throws the exception
                serializer.Serialize(writer, validator.MatchPossiblyValid("STRING FOR PARSING"), emptyNS);
                stream.Write(Environment.NewLine);
                stream.Flush();

        }
}

1 个答案:

答案 0 :(得分:2)

您正尝试使用单个XmlWriter创建包含多个root elements的XML文件。但是,XML标准每个XML文档需要exactly one root element。您的XmlWriter抛出异常以指示正在创建的XML无效。 (MCVE here。)

如果您确实需要将两个XML文档连接到一个文件中,则可以使用XmlWriters创建的单独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(); }

    conda install theano pygpu=0.6.2

示例XmlWriterSettings.CloseOutput

或者,更好的是,根本不要这样做,因为" XML文档"如上所述,具有多个根是无效的。而是序列化某个容器元素中的两个对象。