Đang cố gắng tuần tự hóa một lớp, ghi vào một tệp XML dưới dạng nhiều phân đoạn, tức là ghi từng đối tượng của lớp như một đoạn riêng lẻ tiêu đề XML/root. Dưới đây là một số mẫu mã:.net XmlSerialize ném "WriteStartDocument không thể được gọi trên các nhà văn được tạo ra với ConformanceLevel.Fragment"
[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();
}
}
}
Trong cuộc gọi đầu tiên để serialize, tôi nhận được ngoại lệ:
WriteStartDocument cannot be called on writers created with ConformanceLevel.Fragment
tôi đang thiếu gì ở đây?
Tuyệt vời, mà chỉ hoạt động tốt. Tôi không quan tâm một chú thích trống trong tệp – sppc42
Lưu ý rằng thuộc tính ['NamespaceHandling'] (http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.namespacehandling.aspx) chỉ tồn tại trong .NET 4.0 trở lên. –
Có thể viết không có gì với 'xmlW.WriteWhitespace (" ")' – oleksa