现在的位置: 首页 > 综合 > 正文

c# 操作xml文件

2014年02月01日 ⁄ 综合 ⁄ 共 6290字 ⁄ 字号 评论关闭

简单创建xml文件:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace CreateXMLByLINQ
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        static string strPath = "Employee.xml";

        //创建XML文件
        private void button1_Click(object sender, EventArgs e)
        {
            XDocument doc = new XDocument(//创建XML文档对象
                new XDeclaration("1.0", "utf-8", "yes"),//添加XML文件声明
                new XElement(textBox1.Text,//创建XML元素
                    new XElement(textBox2.Text, new XAttribute(textBox3.Text, textBox10.Text),//为XML元素添加属性
                        new XElement(textBox4.Text, textBox5.Text),
                        new XElement(textBox6.Text, textBox7.Text),
                        new XElement(textBox8.Text, textBox9.Text))
                    )
                );
            doc.Save(strPath);//保存XML文档
            MessageBox.Show("XML文件创建成功");
        }
    }
}

制作一个这样的界面:

完成

使用LINQ技术对XML文件进行读取:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace QueryXMLByLINQ
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        static string strPath = "Employee.xml";
        static string strID = "";

        //窗体加载时加载XML文件
        private void Form1_Load(object sender, EventArgs e)
        {
            getXmlInfo();
        }

        //显示选中XML节点的详细信息
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            strID = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();//记录选择的职工编号
            XElement xe = XElement.Load(strPath);//加载XML文件
            //使用LINT从XML文件中查询信息
            IEnumerable<XElement> elements = from PInfo in xe.Elements("People")
                                             where PInfo.Attribute("ID").Value == strID
                                             select PInfo;
            foreach (XElement element in elements)//遍历查询结果
            {
                textBox11.Text = element.Element("Name").Value;//显示职工姓名
                comboBox1.SelectedItem = element.Element("Sex").Value;//显示职工性别
                textBox12.Text = element.Element("Salary").Value;//显示职工薪水
            }
        }

        #region 将XML文件内容绑定到DataGridView控件
        /// <summary>
        /// 将XML文件内容绑定到DataGridView控件
        /// </summary>
        private void getXmlInfo()
        {
            DataSet myds = new DataSet();
            myds.ReadXml(strPath);
            dataGridView1.DataSource = myds.Tables[0];
        }
        #endregion
    }
}

文件



删除XML文件中的数据:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace DelXMLByLINQ
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        static string strPath = "Employee.xml";//记录XML文件路径
        static string strID = "";//记录选中的ID编号

        //窗体加载时加载XML文件
        private void Form1_Load(object sender, EventArgs e)
        {
            if (File.Exists(strPath))
            {
                getXmlInfo();
            }
        }

        //删除XML元素
        private void button4_Click(object sender, EventArgs e)
        {
            if (strID != "")//判断是否选择了编号
            {
                XElement xe = XElement.Load(strPath);//加载XML文档
                IEnumerable<XElement> elements = from element in xe.Elements("People")//根据编号查找信息
                                                 where element.Attribute("ID").Value == strID
                                                 select element;
                if (elements.Count() > 0)//判断是否找到了信息
                    elements.First().Remove();//删除找到的XML元素信息
                xe.Save(strPath);//保存XML元素到XML文件
            }
            MessageBox.Show("删除成功");
            getXmlInfo();
        }

        //显示选中XML节点的详细信息
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            strID = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();//记录选中的ID编号
            XElement xe = XElement.Load(strPath);//加载XML文档
            IEnumerable<XElement> elements = from PInfo in xe.Elements("People")//根据编号查找信息
                                             where PInfo.Attribute("ID").Value == strID
                                             select PInfo;
            foreach (XElement element in elements)//遍历查找到的所有信息
            {
                textBox11.Text = element.Element("Name").Value;//显示员工姓名
                comboBox1.SelectedItem = element.Element("Sex").Value;//显示员工性别
                textBox12.Text = element.Element("Salary").Value;//显示员工薪水
            }
        }

        #region 将XML文件内容绑定到DataGridView控件
        /// <summary>
        /// 将XML文件内容绑定到DataGridView控件
        /// </summary>
        private void getXmlInfo()
        {
            DataSet myds = new DataSet();//创建DataSet数据集对象
            myds.ReadXml(strPath);//读取XML结构
            dataGridView1.DataSource = myds.Tables[0];//在DataGridView中显示XML文件中的信息
        }
        #endregion
    }
}

使用LINQ 把SQL转变成XML 显示出来:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;

namespace LinqToXmlConvert
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        private void Frm_Main_Load(object sender, EventArgs e)
        {
            DataClassesDataContext dc = new DataClassesDataContext();//创建LINQ to SQL数据上下文类的对象
            string xmlFilePath = Application.StartupPath + "\\new.xml";//取出xml文件的全路径
            //使用LINQ to XML创建XML
            XDocument doc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("People",
                    from p in dc.tb_Employee//根据LINQ to SQL取出的数据生成XML
                    select new XElement[]{
                new XElement("Person",
                new XAttribute("ID",p.ID),
                new XElement("Name",p.Name),
                new XElement("Sex",p.Sex),
                new XElement("Age", p.Age),
                new XElement("Tel",p.Tel),
                new XElement("QQ",p.QQ),
                new XElement("Email", p.Email),
                new XElement("Address", p.Address)
                )}
                    )
                );
            doc.Save(xmlFilePath);//保存XML文件
            webBrowser1.Url = new Uri(xmlFilePath);//在窗体中呈现XML文件的内容
        }
    }
}

数据如图:

显示效果如图:

读取XML文件更新到数据库:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace XmlToDatabase
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        static string strPath = "Employee.xml";//记录XML文件路径
        //定义数据库连接字符串
        string strCon = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db_TomeTwo.mdf;Integrated Security=True;User Instance=True";
        linqtosqlDataContext linq; //创建Linq连接对象

        //窗体加载时加载XML文件
        private void Form1_Load(object sender, EventArgs e)
        {
            if (File.Exists(strPath))
            {
                getXmlInfo();
            }
        }

        //将数据更新到数据库
        private void btn_Edit_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)//遍历所有行
            {
                linq = new linqtosqlDataContext(strCon);//创建linq连接对象
                tb_XML xml = new tb_XML();//创建tb_XML对象
                xml.ID = dataGridView1.Rows[i].Cells[3].Value.ToString();//为ID赋值
                xml.Name = dataGridView1.Rows[i].Cells[0].Value.ToString();//为Name赋值
                xml.Sex = dataGridView1.Rows[i].Cells[1].Value.ToString();//为Sex赋值
                xml.Salary = Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value);//为Salary赋值
                linq.tb_XML.InsertOnSubmit(xml);//提交数据
                linq.SubmitChanges();//执行对数据库的修改
                linq.Dispose();//释放linq对象
            }
            MessageBox.Show("成功将XML中的数据更新到了数据库中!");//弹出提示
        }

        #region 将XML文件内容绑定到DataGridView控件
        /// <summary>
        /// 将XML文件内容绑定到DataGridView控件
        /// </summary>
        private void getXmlInfo()
        {
            DataSet myds = new DataSet();//创建DataSet数据集对象
            myds.ReadXml(strPath);//读取XML结构
            dataGridView1.DataSource = myds.Tables[0];//在DataGridView中显示XML文件中的信息
        }
        #endregion
    }
}

抱歉!评论已关闭.