VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > c#教程 >
  • C#教程之C#教程之数据字典Dictionary存放键值对

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

1.     方法思路:

使用数据字典【Dictionary<stringstring>】,声明一个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.      对公共方法的调用:

按 Ctrl+C 复制代码
按 Ctrl+C 复制代码

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 }
复制代码

 

存在的就是合理的,总有问题要解决!
相关教程