Xml序列化程序未序列化为有效的 xml

本文关键字:序列化 xml 有效 程序 Xml | 更新日期: 2023-09-27 18:18:48

请考虑以下代码:

public class Obj : IObj
{
    public string Prop1{get;set;}
    public string Prop2{get;set;}
    public string Prop3{get;set;}
}
public static void Persist(IObj obj, string fileFullName)
{
    try
    {
        Directory.CreateDirectory(Path.GetDirectoryName(fileFullName));
        var xmlSerializer = new XmlSerializer(obj.GetType());
        using (var fileStream = File.Open(fileFullName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            xmlSerializer.Serialize(fileStream, obj);
            fileStream.Close();
        }
    }
    catch (Exception e)
    {
       //log
    }
}

第一次在">Obj"上调用">持久"时,我在磁盘上得到一个有效的 xml 文件,如下所示:

<?xml version="1.0"?>
<Obj xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Prop1>value1</Prop1>
    <Prop2>value2</Prop2>
    <Prop2>value3</Prop3>
</Obj>

但是,当在">Obj"上第二次调用">Persist"时(例如,在将">value1"更改为">value"之后(,会在文件末尾添加额外的">">符号,使其无效。

<?xml version="1.0"?>
<Obj xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Prop1>value</Prop1>
    <Prop2>value2</Prop2>
    <Prop2>value3</Prop3>
</Obj>>

我试图调试它但没有发现任何异常,所以我猜它必须这样做以我打开文件的方式。任何帮助解释它将不胜感激。

Xml序列化程序未序列化为有效的 xml

如果文件存在,则打开它并根据需要覆盖任意数量的字节。如果小于当前文件长度,则末尾将有剩余字符。请尝试改用FileMode.Create

我怀疑只有当后续XML小于前一个XML时,您才会看到这一点 - 您需要使用以下内容设置fileStream的长度:

xmlSerializer.Serialize(fileStream, obj);
if (fileStream.CanSeek)
{
     fileStream.SetLength(fileStream.Position);
}

或者,在创建流时指定FileMode.Create

相关文章: