好多大型的項目,把一些固定的參數都存在 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文檔中的單個節點(基類))
完整代碼如下:
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;}}}