2021-3-13 xml的增删改查
生活随笔
收集整理的這篇文章主要介紹了
2021-3-13 xml的增删改查
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
public void XmlAdd(string filename, List<People> pList)
{
try
{
List<People> peoples = XmlDeSerializer(filename);
foreach (var item in pList)
{
People people = new People();
people.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
people.Id = string.IsNullOrEmpty(item.Id) ? "" : item.Id;
people.Age = string.IsNullOrEmpty(item.Age) ? "" : item.Age;
people.Sex = string.IsNullOrEmpty(item.Sex) ? "" : item.Sex;
peoples.Add(people);
}
XmlSerializer x = new XmlSerializer(typeof(List<People>));
TextWriter writer = new StreamWriter(filename);
x.Serialize(writer, peoples);
writer.Dispose();
}
catch (Exception ex)
{ }
}
/// <summary>
/// xml編輯
/// </summary>
/// <param name="filename"></param>
/// <param name="people"></param>
public void XmlEdit(string filename, List<People> pList, int index)
{
try
{
XmlDelete("User", index);
List<People> peoples = XmlDeSerializer(filename);
foreach (var item in pList)
{
People people = new People();
people.Name = string.IsNullOrEmpty(item.Name) ? "" : item.Name;
people.Id = string.IsNullOrEmpty(item.Id) ? "" : item.Id;
people.Age = string.IsNullOrEmpty(item.Age) ? "" : item.Age;
people.Sex = string.IsNullOrEmpty(item.Sex) ? "" : item.Sex;
peoples.Insert(index, people);
}
XmlSerializer x = new XmlSerializer(typeof(List<People>));
TextWriter writer = new StreamWriter(filename);
x.Serialize(writer, peoples);
writer.Dispose();
}
catch (Exception ex)
{ }
}
/// <summary>
/// 刪除列表
/// </summary>
/// <param name="filename"></param>
/// <param name="pList"></param>
public void XmlDelete(string filename, int index = 0)
{
try
{
List<People> peoples = XmlDeSerializer(filename);
peoples.RemoveAt(index);
XmlSerializer x = new XmlSerializer(typeof(List<People>));
TextWriter writer = new StreamWriter(filename);
x.Serialize(writer, peoples);
writer.Dispose();
}
catch (Exception ex)
{ }
}
/// <summary>
/// 顯示列表
/// </summary>
/// <param name="filename"></param>
/// <param name="pList"></param>
public List<People> XmlDeSerializer(string filename)
{
try
{
var mySerializer = new XmlSerializer(typeof(List<People>));
var myFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
if (myFileStream.Length > 0)
{
var myObject = (List<People>)mySerializer.Deserialize(myFileStream);
return myObject;
} myFileStream.Dispose();
return new List<People>();
}
catch (Exception ex)
{
return new List<People>();
}
}
以上是可以放在xmlHelp直接調用的方法
public class People
{
public string Name;
public string Sex;
public string Age;
public string Id;
public People() { }
public People(string Name, string Sex, string Age, string Id)
{
this.Name = Name;
this.Sex = Sex;
this.Age = Age;
this.Id = Id;
} }
總結
以上是生活随笔為你收集整理的2021-3-13 xml的增删改查的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [minio]挂载minio到本地
- 下一篇: Linux中的进程页表