簡體   English   中英

如何從ASPX頁面讀取XML響應

[英]How To Read XML Response From ASPX Page

我正在使用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#語法在屏幕上成功寫入成功,並且如果失敗則讀取失敗的原因並寫入屏幕?

試試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();
        }
    }
}
​

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM