Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read XML Response From Page

I am using C# & ASP.net to perform a POST to a webpage. How can I read the XML response in order to know if my submission had errors or was a success?

This is what I have tried, but it will only return a success/fail message, it will not show me the actual xml returned from the page.

private void Perform()
{
    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=server;Initial Catalog=db;User ID=;Password=";
    sql.Append("select TOP 1 maexst ");
    sql.Append("from redbone.redlight.dbo.maxima ");

    cnn = new SqlConnection(connectionString);
    try
    {
        cnn.Open();
        cmd = new SqlCommand(sql.ToString(), cnn);
        reader = cmd.ExecuteReader();
        while (reader.Read()) { dictFormValues.Add("maexst", reader.GetValue(0).ToString()); }
        reader.Close();
        cmd.Dispose();
        cnn.Close();
    }
    catch (Exception ex) { Response.Write(ex.Message.ToString()); }
    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 = Post(dictFormValues, strPageTitle, strPageURL, ref strError);
    if (blnRet == true)
    {
        this.lblResult.Text = "It was good!";
    }
    else { this.lblResult.Text = strError + ": Error Occured"; }
}

public bool blnRet(Dictionary<string, string> dictFormValues, string strPageTitle, string strPageURL, ref string strMessage)
{
    string strEndpointURL = string.Format("http://testtest12test123.aspx");

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

EDIT

SUCCESS RESPONSE

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

FAIL RESPONSE

<?xml version="1.0" encoding="utf-8" ?>
<result>
   <success>0</success>
   <postid/>
   <errors>
      <error>Error Listed Here</error>
      <error>Error 2 Listed Here</error>
      <error>Error 3 Listed Here</error>
   </errors>
</result>
like image 217
FunFly WhiteGuy Avatar asked Jan 18 '16 20:01

FunFly WhiteGuy


People also ask

How do I get XML data from a website?

Navigate to 'File > New > EasyCatalog Panel > New XML Data Source'; this will open up the 'Data Source Configuration' dialog. In this dialog there will be a drop down next to 'Source:' that is set to 'File' by default. Select 'URL' from this drop down menu.

How do I read XML file as text?

XML files are encoded in plaintext, so you can open them in any text editor and be able to clearly read it. Right-click the XML file and select "Open With." This will display a list of programs to open the file in. Select "Notepad" (Windows) or "TextEdit" (Mac).

How can you load XML data into an HTML page explain with example?

Content as XML string Most of the details of the code are in the script code. Internet Explorer uses the ActiveXObject("Microsoft. XMLDOM") to load XML data into a DOM object, other browsers use the DOMParser() function and parseFromString(text, 'text/xml') method.


1 Answers

Try:

var request = WebRequest.Create("http://some.website/") as HttpWebRequest; 
var response = request.GetResponse();

Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

var result =  readStream.ReadToEnd();

That will put the content of the page in result

What to do next depends on what the response actually is... From there you could use:

  • XmlDocument.LoadXml
  • XDocument.Parse
  • XElement.Parse

Or perhaps something like the HTML Agility Pack will let you parse the response.


Example using XElement

using System.Xml.Linq;
using System.Linq;
using System.Xml;

var xml = System.Xml.Linq.XElement.Parse(result);
if (xml.Elements("success").FirstOrDefault().Value == "1")
{
   // Process Success
   Console.WriteLine("All Worked!");
}
else
{
   var errors = xml.Elements("errors");
   foreach (var error in errors.Elements("error"))
   {
     // read error messages
     Console.WriteLine(error.Value);
   }
}

(Runnable Fiddle)

There's probably a simpler way of parsing the XElement, but that should give you the idea.

like image 179
NikolaiDante Avatar answered Sep 27 '22 20:09

NikolaiDante