.net XmlSerialize抛出“无法在使用ConformanceLevel.Fragment创建的编写器上调用WriteStartDocument”

时间:2013-09-27 08:13:38

标签: c# .net xml serialization xmlserializer

尝试序列化一个类,将XML文件写为多个片段,即将该类的每个对象编写为单个片段,而不使用XML头/根。以下是示例代码:

[Serializable]
public class Test
{
    public int X { get; set; }
    public String Y { get; set; }
    public String[] Z { get; set; }

    public Test()
    {
    }

    public Test(int x, String y, String[] z)
    {
        X = x;
        Y = y;
        Z = z;
    }
}

class Program
{
    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(@"f:\test\test.xml",
                                                   new XmlWriterSettings()
                                                       {ConformanceLevel = ConformanceLevel.Fragment,
                                                        OmitXmlDeclaration = true,
                                                        Indent = true});
            serializer.Serialize(xmlWriter, t1);
            serializer.Serialize(xmlWriter, t2);
            xmlWriter.Close();
        }
    }
}

在第一次序列化调用中,我得到了异常:

WriteStartDocument cannot be called on writers created with ConformanceLevel.Fragment

我在这里缺少什么?

1 个答案:

答案 0 :(得分:13)

这个问题有一个解决方法。在使用序列化程序之前使用xml writer时,将不会写入标头。以下工作正常,但会在xml文件的第一行添加一个空注释标记

按照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();
        }
    }