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. 整体的完整代码块:
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- namespace TestPublicXML
- {
- class Program
- {
- 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();
- }
- 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";
- }
- }
- }
- }
- View Code
来源: http://www.bubuko.com/infodetail-2517037.html