我目前正在与XMLSerializer
一起玩,以了解其工作原理。我能够序列化,保存和反序列化单个对象而不会出现问题。但是,当我尝试反序列化多个对象时遇到了问题。我收到此错误:Unhandled exception. System.InvalidOperationException: There is an error in XML document (10,10).
---> system.xml.XmlException: Unexpected XML declaration. The XML declaration must be the first node in the document,and no whitespace characters are allowed to appear before it.
我已经尝试过这种方法https://stackoverflow.com/a/16416636/8964654 在这里(我可能做错了)
public static ICollection<T> DeserializeList<T>()
{
string filePath = @"TextFiles/Users.txt";
XmlSerializer serializerTool = new XmlSerializer(typeof(User));
List<T> list = new List<T>();
using (FileStream fs = new FileStream (filePath,FileMode.Open)){
while(fs.Position!=fs.Length)
{
//deserialize each object in the file
var deserialized = (T)serializerTool.Deserialize(fs);
//add individual object to a list
list.Add(deserialized);
}
}
//return the list of objects
return list;
}
它不起作用
这是我的原始代码。我特意调用了SaveUser
方法两次,以模拟该方法在不同时间被调用两次
[Serializable]
public class User: ISerializable{
public static void SaveUser(User user){
string filePath = @"TextFiles/Users.txt";
XmlSerializer serializerTool = new XmlSerializer(typeof(User));
using(FileStream fs = new FileStream(filePath,FileMode.Append)){
serializerTool.Serialize(fs,user);
}
}
public static void PrintUser(){
string filePath = @"TextFiles/Users.txt";
XmlSerializer serializerTool = new XmlSerializer(typeof(User));
using (FileStream fs = new FileStream (filePath,FileMode.Open)){
User u1 = (User)serializerTool.Deserialize(fs);
Console.WriteLine($"{u1.FirstName} {u1.LastName},{u1.DOB.ToShortDateString()}");
}
}
}
class Program
{
static void Main(string[] args)
{
User user1 = new User(){
FirstName = "Kim",LastName = "Styles",Address = "500 Penn street,Dallas,46589",username = "KimStyles@yahoo.com",Password ="Kim2019",DOB = (new DateTime(1990,10,01)),Id = 2
};
User user2 = new User(){
FirstName = "Carlos",LastName = "Santana",Address = "500 Amigos street,San Jose,California,username = "Carlos.Santana@yahoo.com",Password ="CarLosSan2019",Id = 2
};
User.SaveUser(user1);
User.SaveUser(user2);
User.PrintUser();
}
}
下面是它如何保存XML数据
<?xml version="1.0"?>
<User xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FirstName>Kim</FirstName>
<LastName>Styles</LastName>
<DOBProxy>Monday,01 October 1990</DOBProxy>
<username>KimStyles@yahoo.com</username>
<Password>Kim2019</Password>
<Address>500 Penn street,46589</Address>
<Id>1</Id>
</User>
<?xml version="1.0"?>
<User xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<FirstName>Carlos</FirstName>
<LastName>Santana</LastName>
<DOBProxy>Monday,01 October 1990</DOBProxy>
<username>Carlos.Santana@yahoo.com</username>
<Password>CarLosSan2019</Password>
<Address>500 Amigos street,46589</Address>
<Id>2</Id>
</User>
我希望能够检索每个用户的所有数据并打印详细信息。我怎样才能做到这一点?有更好的方法吗?