7

クラスをシリアル化して、複数のフラグメントとして 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

ここで何が欠けていますか?

4

1 に答える 1

14

この問題には回避策があります。シリアライザーを使用する前に xml ライターを使用した場合、ヘッダーは書き込まれません。以下は機能しますが、xml ファイルの最初の行に空のコメント タグが追加されます。

オレクサが提案する改善されたコード

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();
        }
    }
于 2013-09-27T09:30:58.383 に答える