在c#中找到xml元素

时间:2017-11-13 10:56:35

标签: c# xml serialization

我正在尝试在公民名单中找到特定元素,但结果始终为空。提前致谢! 这是我正在尝试的代码:

string filepath = "citizens.xml";
if (!File.Exists(filepath))
{
    CitizensList list = new CitizensList();
    Serializer.SerializeObject(filepath, list);
}

CitizensList citizens = Serializer.DeSerializeObject(filepath);
Console.WriteLine("The File {0} has this data", filepath);
citizens.print();


Console.WriteLine("Chose the name of the citizen from the console");        
string name = Console.ReadLine();

CitizensList search = new CitizensList();
var matching = search.Citizen.Find(p => p.FirstName==(name));
if (matching == null)
{
    Console.WriteLine("The Citizen doesn't exists.");
}
else
{
    Serializer.SerializeObject(filepath, citizens);
    citizens = Serializer.DeSerializeObject(filepath);
    search.print();
}

以下是我在xml文件中插入数据的代码,该代码正常工作:

Console.WriteLine("Insert the data of the citizen");
                        Console.WriteLine("Name:");
                        string nm = Console.ReadLine();
                        Console.WriteLine("Surname:");
                        string sn = Console.ReadLine();
                        Console.WriteLine("Email:");
                        string email = Console.ReadLine();
                        Console.WriteLine("Phone:");
                        string no = Console.ReadLine();
                        Citizens citizen = new Citizens();
                        if (citizens.Citizen.Count == 0)
                            citizen.Id = 1;
                        else
                            citizen.Id = Convert.ToInt32(citizens.Citizen.Last<Citizens>().Id) + 1;
                        citizen.FirstName = nm;
                        citizen.Lastname = sn;
                        citizen.Email = email;
                        citizen.PhoneNr = no;
                        citizens.Citizen.Add(citizen);

                        Serializer.SerializeObject(filepath, citizens);
                        citizens = Serializer.DeSerializeObject(filepath);
                        citizens.print();

1 个答案:

答案 0 :(得分:2)

您正在search中搜索,这是一个新创建的(只能假设)列表。

var matching = search.Citizen.Find(p => p.FirstName==(name));

citizens中搜索,您的列表会从文件中读取:

var matching = citizens.Citizen.Find(p => p.FirstName == name);