如何解决从 Xml 中删除元素会在重新加载时破坏格式
我正在创建一个存储车辆数据的系统。当我使用 Xml 序列化来序列化数据时,我得到了正确的格式,如下例所示:
<?xml version="1.0"?>
<ArrayOfVehicle xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Vehicle>
<Registration>fake1</Registration>
<Model>123</Model>
<Make>test</Make>
<Year>1999</Year>
<Cost>100</Cost>
</Vehicle>
<Vehicle>
<Registration>fake2</Registration>
<Model>321</Model>
<Make>123</Make>
<Year>2000</Year>
<Cost>321</Cost>
</Vehicle>
</ArrayOfVehicle>
序列化使用具有在 Xml 文件中看到的属性的车辆列表。我想弄清楚如何从列表中删除车辆并将其序列化回 Xml 文件而不破坏上面显示的格式。
我试图用来从列表中删除记录并序列化和反序列化数据的方法,但是当我删除和项目时,它破坏了格式。这是当我从列表中删除一个项目并序列化它时 Xml 文件的样子:
fake1 123 test 1999 100
这是我删除项目的代码:
for (int i = Business.VehicleList.Count - 1; i >= 0; i--)
{ //Where Business.VehicleList is my list
if (Business.VehicleList[i].Registration == registration)
{
Business.VehicleList.RemoveAt(i);
Business.Save(); //Method for serialization
}
}
这是当我再次尝试反序列化数据时它抛出的错误:
System.InvalidOperationException: 'There is an error in XML document (10,19). XmlException: There are multiple root elements. Line 10,position 19.'
这些是我的序列化和反序列化方法:
public static void Retrieve()
{
using (FileStream fileStream = new FileStream("C:\\temp\\data.xml",FileMode.OpenOrCreate))
{
using (var reader = new StreamReader(fileStream))
{
if (fileStream.Length <= 0)
{
return;
}
else
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<Vehicle>),new XmlRootAttribute("ArrayOfVehicle"));
_vehicleList = (List<Vehicle>)deserializer.Deserialize(reader); //This is where the error is thrown
}
}
}
}
public static void Save()
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Vehicle>));
using (FileStream fileStream = new FileStream("C:\\temp\\data.xml",FileMode.Open))
{
serializer.Serialize(fileStream,VehicleList);
fileStream.Close();
}
}
关于如何在不破坏 Xml 文件的情况下从我的列表中删除车辆的任何建议?
这是我尝试从车辆字符串中删除项目后的来源
<?xml version="1.0"?>
<ArrayOfVehicle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Vehicle>
<Registration>123</Registration>
<Model>123</Model>
<Make>23</Make>
<Year>2000</Year>
<Cost>123</Cost>
</Vehicle>
</ArrayOfVehicle><Registration>1321</Registration>
<Model>123123</Model>
<Make>312312</Make>
<Year>2000</Year>
<Cost>321</Cost>
</Vehicle>
</ArrayOfVehicle>
解决方法
在 Save 方法中,new FileStream("C:\\temp\\data.xml",FileMode.Open)
将打开现有文件而不截断它。所以当你将新的 XML 数据写入文件后,如果新内容比旧内容短,就会有旧内容的残余。
将其更改为 new FileStream("C:\\temp\\data.xml",FileMode.Create)
将解决该问题。
我认为这是因为您正在尝试对格式错误的 xml 进行反序列化。请首先确保您的序列化方法生成正确的 xml。原因可能是因为在 using
语句中关闭了流。并在 for-loop
完成之前序列化列表。
尝试删除 fileStream.Close();
并将 Business.Save();
移到 for-loop
之外。
在这里,我用相同的条件做了一个 fiddle 并且它有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。