我目前正在与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, 46589",
Username = "Carlos.Santana@yahoo.com",
Password ="CarLosSan2019",
DOB = (new DateTime(1990,10,01)),
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, Dallas, 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,San Jose, California, 46589</Address>
<Id>2</Id>
</User>
我希望能够检索每个用户的所有数据并打印详细信息。我怎样才能做到这一点?有更好的方法吗?
答案 0 :(得分:1)
您的xml具有多个根元素,有效的xml不允许这样做。 如果将其更改为格式,则应该可以。
<?xml version="1.0"?>
<Users>
<user></user>
<user></user>
</Users>
答案 1 :(得分:1)
我将按照以下方式解决此问题:
创建 User 类
可序列化类包含用户详细信息。
response.getWriter().append("<table><body>");
for (int i = 1; i < width +1 ; i++) {
response.getWriter().append("<tr>");
for (int j = 1; j < height +1; j++) {
response.getWriter().append("<td>").append(String.format("%4d",i*j)).append("</td>");
}
response.getWriter().append("</tr>");
}
response.getWriter().append("</body></table>");
创建 Users 类
另一个 Serializable 类包含[Serializable]
public class User
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DOB { get; set; }
public override string ToString()
{
return $"{ID}, {FirstName}, {LastName}, {DOB.ToShortDateString()}";
}
}
对象的列表,并处理序列化和反序列化例程:
User
这样,您可以确保XML文件的格式正确,管理用户列表(添加,删除,编辑)。
保存(序列化)示例
[Serializable]
public class Users
{
public List<User> ThisUsers = new List<User>();
public void Save(string filePath)
{
XmlSerializer xs = new XmlSerializer(typeof(Users));
using (StreamWriter sr = new StreamWriter(filePath))
{
xs.Serialize(sr, this);
}
}
public static Users Load(string filePath)
{
Users users;
XmlSerializer xs = new XmlSerializer(typeof(Users));
using (StreamReader sr = new StreamReader(filePath))
{
users = (Users)xs.Deserialize(sr);
}
return users;
}
}
加载(反序列化)示例:
string filePath = @"TextFiles/Users.txt";
Users users = new Users();
for (int i = 1; i < 5; i++)
{
User u = new User
{
ID = i,
FirstName = $"User {i}",
LastName = $"Last Name {i}",
DOB = DateTime.Now.AddYears(-30 + i)
};
users.ThisUsers.Add(u);
}
users.Save(filePath);
这是生成的XML文件的外观
string filePath = @"TextFiles/Users.txt";
Users users = Users.Load(filePath);
users.ThisUsers.ForEach(a => Console.WriteLine(a.ToString()));
//Or get a specific user by id:
Console.WriteLine(users.ThisUsers.Where(b => b.ID == 3).FirstOrDefault()?.ToString());
祝你好运。