1. 程式人生 > >數據字典Dictionary存放鍵值對

數據字典Dictionary存放鍵值對

鍵值 err opened str ner oid read mes name

1. 方法思路:

使用數據字典【Dictionary<string, string>】,聲明一個list集合,將“XML子節點名稱”、“節點值”以鍵【節點名稱】值【節點值】對的形式存入此集合,然後將此集合作為參數傳入封裝的公共方法中即可;

2. 公共方法:

 public static string AssembleXML(Dictionary<string,string> list)
        {
            try
            {
                string strXML = "";
                
foreach (KeyValuePair<string, string> de in list) { strXML += "<" + de.Key + ">" + de.Value + "</" + de.Key + ">"; } return strXML; } catch (Exception ex) { MessageBox.Show(ex.Message,
"組裝XML時出現錯誤:", MessageBoxButtons.OK, MessageBoxIcon.Error); return "0"; } }

3. 對公共方法的調用:

static void Main(string[] args)
        {
            string strXML交換 = "";
            Dictionary<string, string> list = new Dictionary<string, string
>(); list.Add("姓名","張三"); //xml節點、節點值 list.Add("年齡", "20"); string strResult = AssembleXML(list); if (strResult=="0") { MessageBox.Show("組裝xml出現錯誤!"); } else { strXML交換 = @"<?xml version=‘1.0‘ encoding=‘GBK‘?><ROWSET><ROW>" + strResult + "</ROW></ROWSET>"; } Console.WriteLine(strXML交換); Console.ReadKey(); }

4. 整體的完整代碼塊:

技術分享圖片
 1 using System;
 2 using System.Collections;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Windows.Forms;
 7 
 8 namespace TestPublicXML
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             string strXML交換 = "";
15             Dictionary<string, string> list = new Dictionary<string, string>();
16             list.Add("姓名","張三");    //xml節點、節點值
17             list.Add("年齡", "20");         
18             string strResult = AssembleXML(list);
19             if (strResult=="0")
20             {
21                 MessageBox.Show("組裝xml出現錯誤!");
22             }
23             else
24             {
25                 strXML交換 = @"<?xml version=‘1.0‘ encoding=‘GBK‘?><ROWSET><ROW>" + strResult + "</ROW></ROWSET>";             
26             }            
27             Console.WriteLine(strXML交換);
28             Console.ReadKey();             
29         }
30 
31         public static string AssembleXML(Dictionary<string,string> list)
32         {
33             try
34             {
35                 string strXML = "";
36                 foreach (KeyValuePair<string, string> de in list)
37                 {
38                     strXML += "<" + de.Key + ">" + de.Value + "</" + de.Key + ">";
39                 }
40                 return strXML;
41             }
42             catch (Exception ex)
43             {
44                 MessageBox.Show(ex.Message, "組裝XML時出現錯誤:", MessageBoxButtons.OK, MessageBoxIcon.Error);
45                 return "0";
46             }          
47         }
48     }
49 }
View Code

數據字典Dictionary存放鍵值對