如何从ASPX页面读取XML响应

本文关键字:读取 XML 响应 ASPX | 更新日期: 2023-09-27 18:20:52

我使用C#将数据传递到.aspx页面,一切都很好。返回消息现在正在转换为.xml响应,我不知道如何处理读取/写入.xml响应到我的页面以显示失败/成功

这是我实际发送数据的语法

    private void SendData()
    {
        this.lblResult.Text = string.Empty;           
        Dictionary<string, string> dictFormValues = new Dictionary<string, string>();
        string connectionString = null;
        SqlConnection cnn;
        SqlCommand cmd;
        StringBuilder sql = new StringBuilder();
        SqlDataReader reader;
        string email = string.Empty;
        connectionString = "Data Source=titanium;Initial Catalog=DB;User ID=uid;Password=pswd";
        sql.Append("select fullname, address, city, state, zip from testtable");
        cnn = new SqlConnection(connectionString);
        try
        {
            cnn.Open();
            cmd = new SqlCommand(sql.ToString(), cnn);
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                dictFormValues.Add("name", reader.GetValue(0).ToString());
                dictFormValues.Add("address", reader.GetValue(1).ToString());
                dictFormValues.Add("city", reader.GetValue(2).ToString());
                dictFormValues.Add("state", reader.GetValue(3).ToString());
                dictFormValues.Add("zip", reader.GetValue(4).ToString());                    
                fullname = reader.GetValue(0).ToString();
            }
            reader.Close();
            cmd.Dispose();
            cnn.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message.ToString());
        }
        string abcdefg = "";
        string strIpAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
        string strPageTitle = this.Title;
        string strPageURL = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
        string strError = "";
        bool blnRet = false;
        blnRet = PostDataToPage(dictFormValues, abcdefg, strIpAddress, strPageTitle, strPageURL, ref strError);          
        if (blnRet == true)
        {
            this.lblResult.Text = "Success!";
        }
        else
        {
            this.lblResult.Text = strError + ": Fail";
        }
    }
    public bool PostDataToPage(Dictionary<string, string> dictFormValues, string abcdefg, string strIpAddress, string strPageTitle, string strPageURL, ref string strMessage)
    {
        string strEndpointURL = string.Format("http://invalidsite.com/test/");
        System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
        string strPostData = "";
        foreach (var d in dictFormValues)
        {
            strPostData += d.Key + "=" + Server.UrlEncode(d.Value) + "&";
        }
        strPostData += "hs_context=";
        System.Net.HttpWebRequest r = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strEndpointURL);
        r.Method = "POST";
        r.Accept = "application/json";
        r.ContentType = "application/x-www-form-urlencoded";
        r.ContentLength = strPostData.Length;
        r.KeepAlive = false;
        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(r.GetRequestStream()))
        {
            try
            {
                sw.Write(strPostData);
            }
            catch (Exception ex)
            {
                strMessage = ex.Message;
                return false;
            }
        }
        return true;
    }


现在这是将显示成功的语法:

<?xml version="1.0" encoding="utf-8" ?>
<result>
 <success>1</success>
 <successid>12345</successid>
 <errors/>
</result>


这是显示故障的响应

<?xml version="1.0" encoding="utf-8" ?>
<result>
 <success>0</success>
 <successid/>
 <errors>
    <error>Error 1: Too Many Characters</error>
    <error>Error 2: Invalid Entry</error>
 </errors>
</result>


现在,我如何使用我的C#语法来判断是否成功地在屏幕上写入成功,如果失败,则读取失败的原因并写入屏幕?

如何从ASPX页面读取XML响应

尝试xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<?xml version='"1.0'" encoding='"utf-8'" ?>" +
                    "<result>" +
                     "<success>0</success>" +
                     "<successid/>" +
                     "<errors>" +
                        "<error>Error 1: Too Many Characters</error>" +
                        "<error>Error 2: Invalid Entry</error>" +
                     "</errors>" +
                    "</result>";
            XDocument result = XDocument.Parse(xml);
            var parsed = result.Elements().Select(x => new {
                success = (int)x.Element("success"),
                errors = x.Descendants("error") == null ? null : x.Descendants("error").Select(y => y.Value).ToList()
            }).FirstOrDefault();
        }
    }
}
​