简体   繁体   English

如何从ASPX页面读取XML响应

[英]How To Read XML Response From ASPX Page

I am using C# to pass data to an .aspx page and everything works great. 我正在使用C#将数据传递到.aspx页,并且一切正常。 The return message is now being converted over to a .xml response, and I am not sure how to handle reading/writing a .xml response to my page to show failure/success. 现在,返回消息已转换为.xml响应,并且我不确定如何处理对页面的.xml响应读取/写入以显示失败/成功。

This is my syntax on how I actually send the data 这是我实际上如何发送数据的语法

    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;
    }


Now this is the syntax that will show a success: 现在,这将显示出成功的语法:

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


And this is the response that shows failure 这是显示失败的响应

<?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>


Now how can I use my C# syntax to if succesful write success on screen, and if failure read the reason why it failed and write to screen? 现在如何使用C#语法在屏幕上成功写入成功,并且如果失败则读取失败的原因并写入屏幕?

Try xml linq 试试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