欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#读取xml文件到datagridview实例

程序员文章站 2023-12-15 21:21:16
复制代码 代码如下:using system;using system.collections.generic;using system.componentmodel;us...

复制代码 代码如下:

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 version="1.0" encoding="utf-8"?>
-<peoples> -<people id="001"> <name>小王</name> <sex>男</sex> <salary>1500</salary> </people> -<people id="002"> <name>小吕</name> <sex>男</sex> <salary>1500</salary> </people> -<people id="003"> <name>小梁</name> <sex>男</sex> <salary>1500</salary> </people> </peoples>

上一篇:

下一篇: