xml文件
<?xml version="1.0" encoding="utf-8"?><book Type="必修课" ISBN="7-111-19149-2">数据结构严蔚敏30.00<book Type="必修课" ISBN="7-111-19149-3">路由型与交换型互联网基础程庆梅27.00<book Type="选修课" ISBN="7-111-19149-1">计算机操作系统张文明28
加载本地xml
string path = @"C:\Users\asus\Desktop\test.xml"; XElement xe; public MainWindow() { InitializeComponent(); xe= XElement.Load(path); }
自定义一个类
public class BookModel { public BookModel() { } /// /// 所对应的课程类型 /// private string bookType; public string BookType { get { return bookType; } set { bookType = value; } } /// /// 书所对应的ISBN号 /// private string bookISBN; public string BookISBN { get { return bookISBN; } set { bookISBN = value; } } /// /// 书名 /// private string bookName; public string BookName { get { return bookName; } set { bookName = value; } } /// /// 作者 /// private string bookAuthor; public string BookAuthor { get { return bookAuthor; } set { bookAuthor = value; } } /// /// 价格 /// private double bookPrice; public double BookPrice { get { return bookPrice; } set { bookPrice = value; } } }
增
private void Button_Click(object sender, RoutedEventArgs e) { XElement record = new XElement( new XElement("book", new XAttribute("Type", "选修课"), new XAttribute("ISBN", "7-111-19149-1"), new XElement("title", "计算机操作系统"), new XElement("author", "张文明"), new XElement("price", 28.00))); xe.Add(record); xe.Save(path); }
删
private void Button_Click_1(object sender, RoutedEventArgs e) { foreach (var item in xe.Elements("book").Where(x => x.Attribute("ISBN").Value== "7-111-19149-1").ToList()) { item.Remove(); } xe.Save(path); }
改
private void Button_Click_2(object sender, RoutedEventArgs e) { foreach (var item in xe.Elements("book").Where(x => x.Attribute("ISBN").Value == "7-111-19149-1").ToList()) { item.Element("title").Value = "test"; } xe.Save(path); }
查
private void Button_Click_3(object sender, RoutedEventArgs e) { ListbookModelList = new List(); foreach (var item in xe.Elements("book").Where(x => x.Attribute("ISBN").Value == "7-111-19149-1").ToList()) { BookModel bookModel = new BookModel(); bookModel.BookType = item.Attribute("Type").Value; bookModel.BookISBN = item.Attribute("ISBN").Value; bookModel.BookName = item.Element("title").Value; bookModel.BookPrice =Convert.ToDouble( item.Element("price").Value); bookModel.BookAuthor = item.Element("author").Value; bookModelList.Add(bookModel); } dg1.ItemsSource = bookModelList; }
参考博客:https://www.cnblogs.com/yuer20180726/p/10984234.html