欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C#动态生成XML

程序员文章站 2024-02-18 16:19:40
...

BookInfo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyTest.Model
{   
    /// <summary>  
    /// 图书信息实体类  
    /// </summary>  
    public class BookInfo
    {
        public int BookId { set; get; }             //图书ID  
        public string Title { set; get; }           //图书名称  
        public string Category { set; get; }        //图书分类  
        public string Author { set; get; }          //图书作者  
        public DateTime PublishDate { set; get; }   //出版时间  
        public Double Price { set; get; }           //销售价格  
    }  

}

XmlHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using MyTest.Model;
using System.Xml;

namespace MyTest
{
    public class XmlHelper
    {
        #region 方法1:使用StringBuilder拼接XML
        /// <summary>  
        /// 创建图书信息XML,保存xml文件  
        /// </summary>  
        public void CreateBookXML(string fileName)
        {
            StringBuilder xmlResult = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            List<BookInfo> bookList = GetBookList();    //获取图书列表  
            if (bookList != null && bookList.Count > 0)
            {
                xmlResult.Append("<bookstore>");
                foreach (BookInfo book in bookList)
                {
                    xmlResult.AppendFormat("<book id=\"{0}\" category=\"{1}\">", book.BookId, book.Category);
                    xmlResult.AppendFormat("<title>{0}</title>", book.Title);
                    xmlResult.AppendFormat("<author>{0}</author>", book.Author);
                    xmlResult.AppendFormat("<publishDate>{0}</publishDate>", book.PublishDate.ToString("yyyy-MM-dd"));
                    xmlResult.AppendFormat("<price>{0}</price>", book.Price);
                    xmlResult.Append("</book>");
                }
                xmlResult.Append("</bookstore>");
            }

            //写入文件  
            try
            {
                //1.创建文件流    
                FileStream fileStream = new FileStream(fileName, FileMode.Create);
                //2.创建写入器    
                StreamWriter streamWriter = new StreamWriter(fileStream);
                //3.将内容写入文件    
                streamWriter.WriteLine(xmlResult);
                //4.关闭写入器    
                streamWriter.Close();
                //5.关闭文件流    
                fileStream.Close();
            }
            catch (Exception e)
            { }
        }

        /// <summary>  
        /// 创建图书信息XML,返回XML字符串  
        /// </summary>  
        public string CreateBookXML()
        {
            StringBuilder xmlResult = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            List<BookInfo> bookList = GetBookList();    //获取图书列表  
            if (bookList != null && bookList.Count > 0)
            {
                xmlResult.Append("<bookstore>");
                foreach (BookInfo book in bookList)
                {
                    xmlResult.AppendFormat("<book id=\"{0}\" category=\"{1}\">", book.BookId, book.Category);
                    xmlResult.AppendFormat("<title>{0}</title>", book.Title);
                    xmlResult.AppendFormat("<author>{0}</author>", book.Author);
                    xmlResult.AppendFormat("<publishDate>{0}</publishDate>", book.PublishDate.ToString("yyyy-MM-dd"));
                    xmlResult.AppendFormat("<price>{0}</price>", book.Price);
                    xmlResult.Append("</book>");
                }
                xmlResult.Append("</bookstore>");
            }

            return xmlResult.ToString();

        } 
        #endregion

        #region 方法2:使用XmlTextWriter类创建XML
        /// <summary> 
        /// 创建图书信息XML
        /// </summary>  
        /// <param name="fileName"></param>  
        public void CreateBookXMLOther(string fileName)
        {
            try
            {
                FileStream fileStream = new FileStream(fileName, FileMode.Create);
                XmlTextWriter writer = new XmlTextWriter(fileStream, Encoding.UTF8);
                List<BookInfo> bookList = GetBookList();    //获取图书列表  
                if (bookList != null && bookList.Count > 0)
                {
                    writer.WriteStartDocument();
                    writer.WriteStartElement("bookstore");    //创建父节点  
                    foreach (BookInfo book in bookList)
                    {
                        writer.WriteStartElement("book");    //创建子节点  
                        writer.WriteAttributeString("id", book.BookId.ToString());    //添加属性  
                        writer.WriteAttributeString("category", book.Category);
                        //图书名称节点  
                        writer.WriteStartElement("title");
                        writer.WriteValue(book.Title);    //节点赋值  
                        writer.WriteEndElement();
                        //图书作者节点  
                        writer.WriteStartElement("author");
                        writer.WriteValue(book.Author);
                        writer.WriteEndElement();
                        //出版时间节点  
                        writer.WriteStartElement("publishDate");
                        writer.WriteValue(book.PublishDate.ToString("yyyy-MM-dd"));
                        writer.WriteEndElement();
                        //销售价格节点  
                        writer.WriteStartElement("price");
                        writer.WriteValue(book.Price);
                        writer.WriteEndElement();

                        writer.WriteEndElement();    //子节点结束  
                    }
                    writer.WriteEndElement();    //父节点结束  
                }
                writer.WriteEndDocument();
                writer.Close();
                fileStream.Close();
            }
            catch (Exception e)
            { }
        }   
        #endregion

        /// <summary>  
        /// 获取图书列表,添加模拟数据  
        /// </summary>  
        /// <returns></returns>  
        public List<BookInfo> GetBookList()
        {
            List<BookInfo> bookList = new List<BookInfo>();
            BookInfo book1 = new BookInfo()
            {
                BookId = 1,
                Category = "CHILDREN",
                Title = "H哈利波特",
                Author = "J K.罗琳",
                PublishDate = new DateTime(2005, 08, 15),
                Price = 29.99
            };
            bookList.Add(book1);
            BookInfo book2 = new BookInfo()
            {
                BookId = 2,
                Category = "WEB",
                Title = "学习XML",
                Author = "艾瑞克.雷",
                PublishDate = new DateTime(2003, 10, 18),
                Price = 39.95
            };
            bookList.Add(book2);
            return bookList;
        }  
    }
}

Index.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

namespace MyTest
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //string path = Server.MapPath("~/file/webinfo.xml");
            string xmlStr= new XmlHelper().CreateBookXML();

            Response.ContentType = "text/xml";
            Response.Charset = "UTF-8";
            Response.Write(xmlStr);
            Response.End();   
        }


    }
}

运行结果如图:

C#动态生成XML


UnifiedOrder.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyTest.WechatModel
{
    /// <summary>
    /// 微信统一接口请求实体对象
    /// </summary>
    [Serializable]
    public class UnifiedOrder
    {
        /// <summary>
        /// 公共号ID(微信分配的公众账号 ID)
        /// </summary>
        public string appid = "";
        /// <summary>
        /// 商户号(微信支付分配的商户号)
        /// </summary>
        public string mch_id = "";
        /// <summary>
        /// 微信支付分配的终端设备号
        /// </summary>
        public string device_info = "";
        /// <summary>
        /// 随机字符串,不长于 32 位
        /// </summary>
        public string nonce_str = "";
        /// <summary>
        /// 签名
        /// </summary>
        public string sign = "";
        /// <summary>
        /// 商品描述
        /// </summary>
        public string body = "";
        /// <summary>
        /// 附加数据,原样返回
        /// </summary>
        public string attach = "";
        /// <summary>
        /// 商户系统内部的订单号,32个字符内、可包含字母,确保在商户系统唯一,详细说明
        /// </summary>
        public string out_trade_no = "";
        /// <summary>
        /// 订单总金额,单位为分,不能带小数点
        /// </summary>
        public int total_fee = 0;
        /// <summary>
        /// 终端IP
        /// </summary>
        public string spbill_create_ip = "";
        /// <summary>
        /// 订 单 生 成 时 间 , 格 式 为yyyyMMddHHmmss,如 2009 年12 月 25 日 9 点 10 分 10 秒表示为 20091225091010。时区为 GMT+8 beijing。该时间取自商户服务器
        /// </summary>
        public string time_start = "";
        /// <summary>
        /// 交易结束时间
        /// </summary>
        public string time_expire = "";
        /// <summary>
        /// 商品标记 商品标记,该字段不能随便填,不使用请填空,使用说明详见第 5 节
        /// </summary>
        public string goods_tag = "";
        /// <summary>
        /// 接收微信支付成功通知
        /// </summary>
        public string notify_url = "";
        /// <summary>
        /// JSAPI、NATIVE、APP
        /// </summary>
        public string trade_type = "";
        /// <summary>
        /// 用户标识 trade_type 为 JSAPI时,此参数必传
        /// </summary>
        public string openid = "";
        /// <summary>
        /// 只在 trade_type 为 NATIVE时需要填写。
        /// </summary>
        public string product_id = "";
    }
}

QueryOrder.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyTest.WechatModel
{
    /// <summary>
    /// 微信订单查询接口请求实体对象
    /// </summary>
    [Serializable]
    public class QueryOrder
    {
        /// <summary>
        /// 公共号ID(微信分配的公众账号 ID)
        /// </summary>
        public string appid = "";

        /// <summary>
        /// 商户号(微信支付分配的商户号)
        /// </summary>
        public string mch_id = "";

        /// <summary>
        /// 微信订单号,优先使用
        /// </summary>
        public string transaction_id = "";

        /// <summary>
        /// 商户系统内部订单号
        /// </summary>
        public string out_trade_no = "";

        /// <summary>
        /// 随机字符串,不长于 32 位
        /// </summary>
        public string nonce_str = "";

        /// <summary>
        /// 签名,参与签名参数:appid,mch_id,transaction_id,out_trade_no,nonce_str,key
        /// </summary>
        public string sign = "";
    }
}

OrderDetail.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyTest.WechatModel
{
    /// <summary>
    /// 微信订单明细实体对象
    /// </summary>
    [Serializable]
    public class OrderDetail
    {
        /// <summary>
        /// 返回状态码,SUCCESS/FAIL 此字段是通信标识,非交易标识,交易是否成功需要查看trade_state来判断
        /// </summary>
        public string return_code = "";

        /// <summary>
        /// 返回信息返回信息,如非空,为错误原因 签名失败 参数格式校验错误
        /// </summary>
        public string return_msg = "";

        /// <summary>
        /// 公共号ID(微信分配的公众账号 ID)
        /// </summary>
        public string appid = "";

        /// <summary>
        /// 商户号(微信支付分配的商户号)
        /// </summary>
        public string mch_id = "";

        /// <summary>
        /// 随机字符串,不长于32位
        /// </summary>
        public string nonce_str = "";

        /// <summary>
        /// 签名
        /// </summary>
        public string sign = "";

        /// <summary>
        /// 业务结果,SUCCESS/FAIL
        /// </summary>
        public string result_code = "";

        /// <summary>
        /// 错误代码
        /// </summary>
        public string err_code = "";

        /// <summary>
        /// 错误代码描述
        /// </summary>
        public string err_code_des = "";

        /// <summary>
        /// 交易状态
        ///SUCCESS—支付成功
        ///REFUND—转入退款
        ///NOTPAY—未支付
        ///CLOSED—已关闭
        ///REVOKED—已撤销
        ///USERPAYING--用户支付中
        ///NOPAY--未支付(输入密码或确认支付超时) PAYERROR--支付失败(其他原因,如银行返回失败)
        /// </summary>
        public string trade_state = "";

        /// <summary>
        /// 微信支付分配的终端设备号
        /// </summary>
        public string device_info = "";

        /// <summary>
        /// 用户在商户appid下的唯一标识
        /// </summary>
        public string openid = "";

        /// <summary>
        /// 用户是否关注公众账号,Y-关注,N-未关注,仅在公众账号类型支付有效
        /// </summary>
        public string is_subscribe = "";

        /// <summary>
        /// 交易类型,JSAPI、NATIVE、MICROPAY、APP
        /// </summary>
        public string trade_type = "";

        /// <summary>
        /// 银行类型,采用字符串类型的银行标识
        /// </summary>
        public string bank_type = "";

        /// <summary>
        /// 订单总金额,单位为分
        /// </summary>
        public string total_fee = "";

        /// <summary>
        /// 现金券支付金额<=订单总金额,订单总金额-现金券金额为现金支付金额
        /// </summary>
        public string coupon_fee = "";

        /// <summary>
        /// 货币类型,符合ISO 4217标准的三位字母代码,默认人民币:CNY
        /// </summary>
        public string fee_type = "";

        /// <summary>
        /// 微信支付订单号
        /// </summary>
        public string transaction_id = "";

        /// <summary>
        /// 商户系统的订单号,与请求一致。
        /// </summary>
        public string out_trade_no = "";

        /// <summary>
        /// 商家数据包,原样返回
        /// </summary>
        public string attach = "";

        /// <summary>
        /// 支付完成时间,格式为yyyyMMddhhmmss,如2009年12月27日9点10分10秒表示为20091227091010。
        /// 时区为GMT+8 beijing。该时间取自微信支付服务器
        /// </summary>
        public string time_end = "";

    }
}

EnterParam.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyTest.WechatModel
{
    /// <summary>
    /// 微信接入参数
    /// </summary>
    public class EnterParam
    {
        /// <summary>
        /// 是否加密
        /// </summary>
        public bool IsAes { get; set; }
        /// <summary>
        /// 接入token
        /// </summary>
        public string token { get; set; }
        /// <summary>
        ///微信appid
        /// </summary>
        public string appid { get; set; }
        /// <summary>
        /// 加***
        /// </summary>
        public string EncodingAESKey { get; set; }
    }
}

WechatXmlHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using MyTest.Model;
using System.Xml;
using System.Collections;
using MyTest.WechatModel;

namespace MyTest
{
    public class WechatXmlHelper
    {
        /// <summary>
        /// 微信统一下单接口xml参数整理
        /// </summary>
        /// <param name="order">微信支付参数实例</param>
        /// <param name="key">**</param>
        /// <returns></returns>
        protected string getUnifiedOrderXml(UnifiedOrder order, string key)
        {
            string return_string = string.Empty;
            SortedDictionary<string, string> sParams = new SortedDictionary<string, string>();
            sParams.Add("appid", order.appid);
            sParams.Add("attach", order.attach);
            sParams.Add("body", order.body);
            sParams.Add("device_info", order.device_info);
            sParams.Add("mch_id", order.mch_id);
            sParams.Add("nonce_str", order.nonce_str);
            sParams.Add("notify_url", order.notify_url);
            sParams.Add("openid", order.openid);
            sParams.Add("out_trade_no", order.out_trade_no);
            sParams.Add("spbill_create_ip", order.spbill_create_ip);
            sParams.Add("total_fee", order.total_fee.ToString());
            sParams.Add("trade_type", order.trade_type);
            order.sign = "0ca175b9c0f726a831d895e269332461"; //getsign(sParams, key);
            sParams.Add("sign", order.sign);

            //拼接成XML请求数据
            StringBuilder sbPay = new StringBuilder();
            foreach (KeyValuePair<string, string> k in sParams)
            {
                if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
                {
                    sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                }
                else
                {
                    sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
                }
            }
            return_string = string.Format("<xml>{0}</xml>", sbPay.ToString());
            byte[] byteArray = Encoding.UTF8.GetBytes(return_string);
            return_string = Encoding.GetEncoding("GBK").GetString(byteArray);
            return return_string;

        }

        /// <summary>
        /// 微信订单查询接口XML参数整理
        /// </summary>
        /// <param name="queryorder">微信订单查询参数实例</param>
        /// <param name="key">**</param>
        /// <returns></returns>
        protected string getQueryOrderXml(QueryOrder queryorder, string key)
        {
            string return_string = string.Empty;
            SortedDictionary<string, string> sParams = new SortedDictionary<string, string>();
            sParams.Add("appid", queryorder.appid);
            sParams.Add("mch_id", queryorder.mch_id);
            sParams.Add("transaction_id", queryorder.transaction_id);
            sParams.Add("out_trade_no", queryorder.out_trade_no);
            sParams.Add("nonce_str", queryorder.nonce_str);
            queryorder.sign = "0ca175b9c0f726a831d895e269332461"; //getsign(sParams, key);
            sParams.Add("sign", queryorder.sign);

            //拼接成XML请求数据
            StringBuilder sbPay = new StringBuilder();
            foreach (KeyValuePair<string, string> k in sParams)
            {
                if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
                {
                    sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                }
                else
                {
                    sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
                }
            }
            return_string = string.Format("<xml>{0}</xml>", sbPay.ToString().TrimEnd(','));
            return return_string;
        }


        //输出XML
        public string parseXML(Hashtable hashT)
        {
            Hashtable parameters = hashT;
            StringBuilder sb = new StringBuilder();
            sb.Append("<xml>");
            int iIsNumber = 0;
            foreach (string k in parameters.Keys)
            {
                string v = (string)parameters[k];
                if (int.TryParse(v, out iIsNumber))
                {
                    sb.Append("<" + k + ">" + v + "</" + k + ">");
                }
                else
                {
                    sb.Append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
                }
            }
            sb.Append("</xml>");
            return sb.ToString();
        }


        /// <summary>
        /// 返回微信POST过来的结果(微信信息返回)
        /// </summary>
        /// <param name="weixinXML">微信服务器post过来的数据</param>
        private string ResponseMsg(string weixinXML)
        {
            Hashtable ht = new Hashtable(); //GetXmlName(weixinXML);

            //这里写你的返回信息代码
            StringBuilder sb = new StringBuilder();
            sb.Append("<xml>");
            sb.Append("<ToUserName><![CDATA[" + ht["FromUserName"].ToString() + "]]></ToUserName>");
            sb.Append("<FromUserName><![CDATA[" + ht["ToUserName"].ToString() + "]]></FromUserName>");
            sb.Append("<CreateTime>" + ht["CreateTime"].ToString() + "</CreateTime>");

            sb.Append("<MsgType><![CDATA[" + ht["MsgType"].ToString() + "]]></MsgType>");
            sb.Append("<Content><![CDATA[" + ht["Content"].ToString() + "]]></Content>");
            sb.Append("</xml>");
            return sb.ToString();
        }


        /// <summary>
        /// 开发者微信号
        /// </summary>
        public string ToUserName { get; set; }
        /// <summary>
        /// 发送方帐号(一个OpenID)
        /// </summary>
        public string FromUserName { get; set; }
        /// <summary>
        /// 消息创建时间 (整型)
        /// </summary>
        public string CreateTime { get; set; }

        /// <summary>
        /// 消息类型
        /// </summary>
        //public MsgType MsgType { get; set; }
        //public  void ResText(EnterParam param, string content)
        //{
        //    StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now)));
        //    resxml.AppendFormat("<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{0}]]></Content><FuncFlag>0</FuncFlag></xml>", content);

        //}

        /// <summary>
        /// 回复消息(音乐)
        /// </summary>
        //public void ResMusic(EnterParam param, Music mu)
        //{
        //    StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now)));
        //    resxml.Append(" <MsgType><![CDATA[music]]></MsgType>");
        //    resxml.AppendFormat("<Music><Title><![CDATA[{0}]]></Title><Description><![CDATA[{1}]]></Description>", mu.Title, mu.Description);
        //    resxml.AppendFormat("<MusicUrl><![CDATA[http://{0}{1}]]></MusicUrl><HQMusicUrl><![CDATA[http://{2}{3}]]></HQMusicUrl></Music><FuncFlag>0</FuncFlag></xml>", VqiRequest.GetCurrentFullHost(), mu.MusicUrl, VqiRequest.GetCurrentFullHost(), mu.HQMusicUrl);

        //}


        //public void ResVideo(EnterParam param, Video v)
        //{
        //    StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now)));
        //    resxml.Append(" <MsgType><![CDATA[video]]></MsgType>");
        //    resxml.AppendFormat("<Video><MediaId><![CDATA[{0}]]></MediaId>", v.media_id);
        //    resxml.AppendFormat("<Title><![CDATA[{0}]]></Title>", v.title);
        //    resxml.AppendFormat("<Description><![CDATA[{0}]]></Description></Video></xml>", v.description);

        //}

        /// <summary>
        /// 回复消息(图片)
        /// </summary>
        //public void ResPicture(EnterParam param, Picture pic, string domain)
        //{
        //    StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now)));
        //    resxml.Append(" <MsgType><![CDATA[image]]></MsgType>");
        //    resxml.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl></xml>", domain + pic.PictureUrl);

        //}

        /// <summary>
        /// 回复消息(图文列表)
        /// </summary>
        /// <param name="param"></param>
        /// <param name="art"></param>
        //public void ResArticles(EnterParam param, List<Articles> art)
        //{
        //    StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now)));
        //    resxml.AppendFormat("<MsgType><![CDATA[news]]></MsgType><ArticleCount>{0}</ArticleCount><Articles>", art.Count);
        //    for (int i = 0; i < art.Count; i++)
        //    {
        //        resxml.AppendFormat("<item><Title><![CDATA[{0}]]></Title>  <Description><![CDATA[{1}]]></Description>", art[i].Title, art[i].Description);
        //        resxml.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl><Url><![CDATA[{1}]]></Url></item>", art[i].PicUrl.Contains("http://") ? art[i].PicUrl : "http://" + VqiRequest.GetCurrentFullHost() + art[i].PicUrl, art[i].Url.Contains("http://") ? art[i].Url : "http://" + VqiRequest.GetCurrentFullHost() + art[i].Url);
        //    }
        //    resxml.Append("</Articles><FuncFlag>0</FuncFlag></xml>");

        //}
    }
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Text;
using MyTest.Model;
using System.Xml;
using System.Collections;
using MyTest.WechatModel;

namespace MyTest
{
    public class WechatXmlHelper
    {
        /// <summary>
        /// 微信统一下单接口xml参数整理
        /// </summary>
        /// <param name="order">微信支付参数实例</param>
        /// <param name="key">**</param>
        /// <returns></returns>
        protected string getUnifiedOrderXml(UnifiedOrder order, string key)
        {
            string return_string = string.Empty;
            SortedDictionary<string, string> sParams = new SortedDictionary<string, string>();
            sParams.Add("appid", order.appid);
            sParams.Add("attach", order.attach);
            sParams.Add("body", order.body);
            sParams.Add("device_info", order.device_info);
            sParams.Add("mch_id", order.mch_id);
            sParams.Add("nonce_str", order.nonce_str);
            sParams.Add("notify_url", order.notify_url);
            sParams.Add("openid", order.openid);
            sParams.Add("out_trade_no", order.out_trade_no);
            sParams.Add("spbill_create_ip", order.spbill_create_ip);
            sParams.Add("total_fee", order.total_fee.ToString());
            sParams.Add("trade_type", order.trade_type);
            order.sign = "0ca175b9c0f726a831d895e269332461"; //getsign(sParams, key);
            sParams.Add("sign", order.sign);

            //拼接成XML请求数据
            StringBuilder sbPay = new StringBuilder();
            foreach (KeyValuePair<string, string> k in sParams)
            {
                if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
                {
                    sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                }
                else
                {
                    sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
                }
            }
            return_string = string.Format("<xml>{0}</xml>", sbPay.ToString());
            byte[] byteArray = Encoding.UTF8.GetBytes(return_string);
            return_string = Encoding.GetEncoding("GBK").GetString(byteArray);
            return return_string;

        }

        /// <summary>
        /// 微信订单查询接口XML参数整理
        /// </summary>
        /// <param name="queryorder">微信订单查询参数实例</param>
        /// <param name="key">**</param>
        /// <returns></returns>
        protected string getQueryOrderXml(QueryOrder queryorder, string key)
        {
            string return_string = string.Empty;
            SortedDictionary<string, string> sParams = new SortedDictionary<string, string>();
            sParams.Add("appid", queryorder.appid);
            sParams.Add("mch_id", queryorder.mch_id);
            sParams.Add("transaction_id", queryorder.transaction_id);
            sParams.Add("out_trade_no", queryorder.out_trade_no);
            sParams.Add("nonce_str", queryorder.nonce_str);
            queryorder.sign = "0ca175b9c0f726a831d895e269332461"; //getsign(sParams, key);
            sParams.Add("sign", queryorder.sign);

            //拼接成XML请求数据
            StringBuilder sbPay = new StringBuilder();
            foreach (KeyValuePair<string, string> k in sParams)
            {
                if (k.Key == "attach" || k.Key == "body" || k.Key == "sign")
                {
                    sbPay.Append("<" + k.Key + "><![CDATA[" + k.Value + "]]></" + k.Key + ">");
                }
                else
                {
                    sbPay.Append("<" + k.Key + ">" + k.Value + "</" + k.Key + ">");
                }
            }
            return_string = string.Format("<xml>{0}</xml>", sbPay.ToString().TrimEnd(','));
            return return_string;
        }


        //输出XML
        public string parseXML(Hashtable hashT)
        {
            Hashtable parameters = hashT;
            StringBuilder sb = new StringBuilder();
            sb.Append("<xml>");
            int iIsNumber = 0;
            foreach (string k in parameters.Keys)
            {
                string v = (string)parameters[k];
                if (int.TryParse(v, out iIsNumber))
                {
                    sb.Append("<" + k + ">" + v + "</" + k + ">");
                }
                else
                {
                    sb.Append("<" + k + "><![CDATA[" + v + "]]></" + k + ">");
                }
            }
            sb.Append("</xml>");
            return sb.ToString();
        }


        /// <summary>
        /// 返回微信POST过来的结果(微信信息返回)
        /// </summary>
        /// <param name="weixinXML">微信服务器post过来的数据</param>
        private string ResponseMsg(string weixinXML)
        {
            Hashtable ht = new Hashtable(); //GetXmlName(weixinXML);

            //这里写你的返回信息代码
            StringBuilder sb = new StringBuilder();
            sb.Append("<xml>");
            sb.Append("<ToUserName><![CDATA[" + ht["FromUserName"].ToString() + "]]></ToUserName>");
            sb.Append("<FromUserName><![CDATA[" + ht["ToUserName"].ToString() + "]]></FromUserName>");
            sb.Append("<CreateTime>" + ht["CreateTime"].ToString() + "</CreateTime>");

            sb.Append("<MsgType><![CDATA[" + ht["MsgType"].ToString() + "]]></MsgType>");
            sb.Append("<Content><![CDATA[" + ht["Content"].ToString() + "]]></Content>");
            sb.Append("</xml>");
            return sb.ToString();
        }


        /// <summary>
        /// 开发者微信号
        /// </summary>
        public string ToUserName { get; set; }
        /// <summary>
        /// 发送方帐号(一个OpenID)
        /// </summary>
        public string FromUserName { get; set; }
        /// <summary>
        /// 消息创建时间 (整型)
        /// </summary>
        public string CreateTime { get; set; }

        /// <summary>
        /// 消息类型
        /// </summary>
        //public MsgType MsgType { get; set; }
        //public  void ResText(EnterParam param, string content)
        //{
        //    StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now)));
        //    resxml.AppendFormat("<MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{0}]]></Content><FuncFlag>0</FuncFlag></xml>", content);

        //}

        /// <summary>
        /// 回复消息(音乐)
        /// </summary>
        //public void ResMusic(EnterParam param, Music mu)
        //{
        //    StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now)));
        //    resxml.Append(" <MsgType><![CDATA[music]]></MsgType>");
        //    resxml.AppendFormat("<Music><Title><![CDATA[{0}]]></Title><Description><![CDATA[{1}]]></Description>", mu.Title, mu.Description);
        //    resxml.AppendFormat("<MusicUrl><![CDATA[http://{0}{1}]]></MusicUrl><HQMusicUrl><![CDATA[http://{2}{3}]]></HQMusicUrl></Music><FuncFlag>0</FuncFlag></xml>", VqiRequest.GetCurrentFullHost(), mu.MusicUrl, VqiRequest.GetCurrentFullHost(), mu.HQMusicUrl);

        //}


        //public void ResVideo(EnterParam param, Video v)
        //{
        //    StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now)));
        //    resxml.Append(" <MsgType><![CDATA[video]]></MsgType>");
        //    resxml.AppendFormat("<Video><MediaId><![CDATA[{0}]]></MediaId>", v.media_id);
        //    resxml.AppendFormat("<Title><![CDATA[{0}]]></Title>", v.title);
        //    resxml.AppendFormat("<Description><![CDATA[{0}]]></Description></Video></xml>", v.description);

        //}

        /// <summary>
        /// 回复消息(图片)
        /// </summary>
        //public void ResPicture(EnterParam param, Picture pic, string domain)
        //{
        //    StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now)));
        //    resxml.Append(" <MsgType><![CDATA[image]]></MsgType>");
        //    resxml.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl></xml>", domain + pic.PictureUrl);

        //}

        /// <summary>
        /// 回复消息(图文列表)
        /// </summary>
        /// <param name="param"></param>
        /// <param name="art"></param>
        //public void ResArticles(EnterParam param, List<Articles> art)
        //{
        //    StringBuilder resxml = new StringBuilder(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime>", FromUserName, ToUserName, Utils.ConvertDateTimeInt(DateTime.Now)));
        //    resxml.AppendFormat("<MsgType><![CDATA[news]]></MsgType><ArticleCount>{0}</ArticleCount><Articles>", art.Count);
        //    for (int i = 0; i < art.Count; i++)
        //    {
        //        resxml.AppendFormat("<item><Title><![CDATA[{0}]]></Title>  <Description><![CDATA[{1}]]></Description>", art[i].Title, art[i].Description);
        //        resxml.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl><Url><![CDATA[{1}]]></Url></item>", art[i].PicUrl.Contains("http://") ? art[i].PicUrl : "http://" + VqiRequest.GetCurrentFullHost() + art[i].PicUrl, art[i].Url.Contains("http://") ? art[i].Url : "http://" + VqiRequest.GetCurrentFullHost() + art[i].Url);
        //    }
        //    resxml.Append("</Articles><FuncFlag>0</FuncFlag></xml>");

        //}
    }
}

WechatXml.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

namespace MyTest
{
    public partial class WechatXml : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Hashtable ht = new Hashtable();
            ht.Add("Name", "wu");
            ht.Add("Age", "27");
            ht.Add("Country", "American");
            ht.Add("Job", "NET高级开发");
            ht.Add("Interesting", "电影,书籍");


            WechatXmlHelper helper = new WechatXmlHelper();
            string xmlStr = helper.parseXML(ht);
            Response.ContentType = "text/xml";
            Response.Charset = "UTF-8";
            Response.Write(xmlStr);
            Response.End();   
        }
    }
}

运行结果如图:

C#动态生成XML