C# Linq方式生成SAP对接的XML格式内容(一般处理程序 ashx )

Linq生成XML的方法:

 string CreateXML(string strkey, string strDATAJSON)
        {

            XDeclaration dec = new XDeclaration("1.0", "UTF-8", null);
            XDocument xdoc = new XDocument();
            XNamespace saop = "http://schemas.xmlsoap.org/soap/envelope/";
            XNamespace ns0 = "http://www.db.com";
            XElement root = new XElement(saop + "Envelope",                 
                     new XAttribute(XNamespace.Xmlns + "soap", "http://schemas.xmlsoap.org/soap/envelope/"),
                      new XElement(saop + "Body",
                      new XElement(ns0 + "MT_COMMON_RET",
                new XAttribute(XNamespace.Xmlns + "ns0", "http://www.db.com"),
                          new XElement("KEY", strkey),
                new XElement("DATAJSON_RET", strDATAJSON)))
                
            );
            xdoc.Add(root);
            string strdoc = dec.ToString();//@"<?xml version=""1.0"" encoding=""utf-8""?>";
            return strdoc + xdoc.ToString();

        }
View Code

生成结果格式:

<?xml version="1.0" encoding="UTF-8"?>

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">


<soap:Body>


<ns0:MT_COMMON_RET xmlns:ns0="http://www.db.com">

<KEY>DB_XZQYSJTB</KEY>

<DATAJSON_RET>{"MANTD":"0000","MANTR":"0000"}</DATAJSON_RET>

</ns0:MT_COMMON_RET>

</soap:Body>

</soap:Envelope>
View Code

访问方法:

 public void ProcessRequest(HttpContext context)
        {

            int rowcount = (int)context.Request.InputStream.Length;
            byte[] buff = new byte[rowcount];
            context.Request.InputStream.Read(buff, 0, rowcount);
            string text = System.Text.Encoding.UTF8.GetString(buff);
            Log4.WriteLog("Handler非标接收数据:" + text ?? "");
/***********************************************************/
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("AAA", "0000");
            dic.Add("BBB", "0000");
            string strDATAJSON = Common.Tools.ConvertToJsonStr(dic);
            string strxml = CreateXML("KEY值", strDATAJSON);
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.Response.AddHeader("Content-Length", strxml.Length.ToString()); 
            context.Response.ContentType = "text/xml";
            context.Response.Write(strxml);
            context.Response.Flush();
            context.Response.End();         

        }

 

posted @ 2019-07-10 14:28  一叶孤城  阅读(356)  评论(0)    收藏  举报