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 "";
}
}
3. 对公共方法的调用:
static void Main(string[] args)
{
string strXML交换 = "";
Dictionary<string, string> list = new Dictionary<string, string>();
list.Add("姓名","张三"); //xml节点、节点值
list.Add("年龄", "");
string strResult = AssembleXML(list);
if (strResult=="")
{
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("年龄", "");
string strResult = AssembleXML(list);
if (strResult=="")
{
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 "";
}
}
}
}