我正在尝试使用以下代码将数据保存为xml
StorageFile file = await dataFolder.CreateFileAsync(filename,
CreationCollisionOption.OpenIfExists);
// Serialize the object
XmlSerializer serializer = new XmlSerializer(obj.GetType());
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
try
{
s.Position = s.Seek(0, SeekOrigin.End);
serializer.Serialize(s, obj);
}
catch (Exception ex)
{
Console.Out.WriteLine(ex.Message);
}
finally{
s.Close();
}
}
这会产生格式为的xml:
<?xml version="1.0" encoding="utf-8"?>
<Tasks xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Task>task1</Task>
<Group>group</Group>
....
</Tasks>
问题
当我附加到文件时,我得到类似的东西
<?xml version="1.0" encoding="utf-8"?>
<Tasks xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Task>task1</Task>
<Group>group</Group>
....
</Tasks><?xml version="1.0" encoding="utf-8"?>
<Tasks xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Task>task2</Task>
<Group>group</Group>
....
</Tasks>
这可以防止数据反序列化,如何避免编写元数据?
答案 0 :(得分:1)
您应该使用XmlTextWriter
(XmlTextWriter class)来更好地控制XML。请尝试以下方法:
StorageFile file = await dataFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
// Serialize the object
XmlSerializer serializer = new XmlSerializer(obj.GetType());
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
try
{
s.Position = s.Seek(0, SeekOrigin.End);
using (var x = XmlWriter.Create(s, new XmlWriterSettings(){OmitXmlDeclaration = true}))
{
x.Setting.OmitXmlDeclaration = true;
serializer.Serialize(x, obj);
}
}
catch (Exception ex)
{
Console.Out.WriteLine(ex.Message);
}
finally{
s.Close();
}
}
编辑:new XmlTextWriter
替换XmlWriter.Create