C# datagridview读取XML数据和保存到XML的例子
C# 的XML类型较多,本次介绍的XML格式如下:
<?xml version="1.0" encoding="utf-8"?>
<Products exportDate="2025-10-07 18:32:57">
<Product code="A001" category="fruit" price="16.55" stock="100" />
<Product code="A002" category="vegetable" price="10" stock="50" />
<Product code="A003" category="fruit" price="6.00" stock="80" />
<Product code="A004" category="dairy" price="8.00" stock="30" />
</Products>
由于单行保存的数据较多,比较常用
下面先介绍程序界面:
界面有包含一个datagridview空间和一个保存控件
代码如下:
form load用于读取XML的文件
保存按钮用于把datagridviw的内容保存到XML文件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace XML1
{
public partial class Form1: Form
{
string txtFilePath;
public Form1()
{
InitializeComponent();
string s1 = Application.StartupPath;
string s2 = s1.Substring(0, s1.LastIndexOf("\\bin") + 1);
DirectoryInfo path = new DirectoryInfo(s2 + "Config");
path.Create();
txtFilePath = Path.Combine(s2, "Config", "Products.xml");
}
private void Form1_Load(object sender, EventArgs e)
{
DataTable datatable1 =