[英]find xml element in c#
我正在嘗試在市民列表中查找特定元素,但結果始終為null。 提前致謝! 這是我正在嘗試的代碼:
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();
您正在search
中search
,這是一個新創建的(只能假設) 空列表。
var matching = search.Citizen.Find(p => p.FirstName==(name));
您應該在搜索citizens
,您的列表從文件中讀取:
var matching = citizens.Citizen.Find(p => p.FirstName == name);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.