.net XmlSerialize 抛出“WriteStartDocument 不能在用 ConformanceLeve

本文关键字:ConformanceLeve 不能 WriteStartDocument XmlSerialize 抛出 net | 更新日期: 2023-09-27 18:33:11

我试图序列化一个类,将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

我在这里错过了什么?

.net XmlSerialize 抛出“WriteStartDocument 不能在用 ConformanceLeve

这个问题

有一个解决方法。如果在使用序列化程序之前使用了 xml 编写器,则不会写入标头。以下内容确实有效,但会在 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();
        }
    }