c# 读取xml文件内的数据

好多大型的项目,把一些固定的参数都存在 xml文件里。

创建c# winfom 项目,test_xml

创建resources文件夹存放xml文件

创建parameters.xml文件

<root>

<test_xml>

<param name ="threshold" value ="128"/>

<param name ="sum_max" value ="100"/>

<param name ="sum_min" value ="50"/>

<param name ="ratio" value ="0.75"/>

<param name ="img_path" value ="C:\\Users\\86957\\Pictures\\CCD\\0243480-20240326103539.jpg"/>

</test_xml>

</root>

根目录root

项目目录test_xml

param+内容

===========================

c# 读取xml文件内的数据的方法如下:

A创建字典用于存放数据:

Dictionary<string, string> Params = new Dictionary<string, string>();

B加载文件:

XmlDocument presentxml = new XmlDocument();

presentxml.Load(FileName);

(XmlDocument属于System.Xml命名空间,是XML文档的内存表示)

C定位:

XmlNodeList paramNodes = presentxml.SelectNodes("/root/test_xml/param");

(XmlNodeList表示通过XPath查询返回的节点集合)

D 读取并写入字典:

foreach (XmlNode node in paramNodes)

{

string name = node.Attributes["name"].Value; // 获取name属性

string value = node.Attributes["value"].Value; // 获取value属性

Params.Add(name, value); // 添加到字典

}

(XmlNode表示XML文档中的单个节点(基类))

完整代码如下:

cs 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace test_xml
{
    public partial class Form1 : Form
    {
        //string xmldata_path = "D:\\VS\\works\\test_xml\\test_xml\\resources\\parameters.xml";//绝对
        string xmldata_path = "../../resources/parameters.xml";//相对
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Dictionary<string, string> Params = new Dictionary<string, string>(ParamXML.ReadParamXML(xmldata_path));

            textBox1.AppendText(Params["threshold"]+"\r\n");
            textBox1.AppendText(Params["img_path"]+"\r\n");
            double difference = (int.Parse(Params["sum_max"]) - int.Parse(Params["sum_min"]))* double.Parse(Params["ratio"]);
            textBox1.AppendText(difference.ToString()+"\r\n");

        }
    }



    class ParamXML
    {
        public static Dictionary<string, string> ReadParamXML(string FileName)
        {
            Dictionary<string, string> Params = new Dictionary<string, string>();
            XmlDocument presentxml = new XmlDocument();
            presentxml.Load(FileName);

            
            XmlNodeList paramNodes = presentxml.SelectNodes("/root/test_xml/param"); // 使用XPath定位节点
            foreach (XmlNode node in paramNodes)
            {
                string name = node.Attributes["name"].Value;  // 获取name属性
                string value = node.Attributes["value"].Value; // 获取value属性
                Params.Add(name, value); // 添加到字典
            }



            return Params;
        }

    }






}