数据字典Dictionary存放键值对
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 }
存在的就是合理的,总有问题要解决!