.net XmlSerialize throws “WriteStartDocument cannot be called on writers created with ConformanceLevel.Fragment”

后端 未结 1 870
清歌不尽
清歌不尽 2021-01-18 07:25

Am trying to serialize a class, writing to an XML file as multiple fragments, i.e, write each object of the class as an individual fragment, without the XML header/root. Bel

相关标签:
1条回答
  • 2021-01-18 08:09

    there is a workaround to this problem. When the xml writer has been used before you use the serializer, then the header won't be written. The following does work, but will add an empty comment tag on the first line of the xml file

    improved code as suggested by oleksa

    static void Main(string[] args)
        {
            Test t1 = new Test(1, "t1", new[] { "a", "b" });
            Test t2 = new Test(2, "t2", new[] { "c", "d", "e" });
    
            XmlSerializer serializer = new XmlSerializer(typeof(Test));
            //using (StreamWriter writer = new StreamWriter(@"f:\test\test.xml"))
            {
                XmlWriter xmlWriter = XmlWriter.Create(@"test.xml",
                                                       new XmlWriterSettings()
                                                       {
                                                           ConformanceLevel = ConformanceLevel.Fragment,
                                                           OmitXmlDeclaration = false,
                                                           Indent = true,
                                                           NamespaceHandling = NamespaceHandling.OmitDuplicates
                                                       });
                xmlWriter.WriteWhitespace("");
                serializer.Serialize(xmlWriter, t1);
                serializer.Serialize(xmlWriter, t2);
                xmlWriter.Close();
            }
        }
    
    0 讨论(0)
提交回复
热议问题