gpt4 book ai didi

c# - XmlSerializer 未序列化为有效的 xml

转载 作者:行者123 更新时间:2023-11-30 13:38:22 25 4
gpt4 key购买 nike

请考虑以下代码:

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”上调用“Persist”时,我在磁盘上得到一个有效的 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>>

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

最佳答案

如果文件存在,您将打开它并根据需要覆盖尽可能多的字节。如果该长度小于当前文件长度,您将在末尾留下剩余字符。尝试改用 FileMode.Create

关于c# - XmlSerializer 未序列化为有效的 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17167704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com