15086

translate xml file to text

Question:

In this web application I want to send an sms to a mobile ann. This is my code of aspx.cs file:

protected void buttonSendOnClick(object sender, EventArgs e) { //are required fields filled in: if (textboxRecipient.Text == "") { textboxError.Text += "Recipient(s) field must not be empty!\n"; textboxError.Visible = true; return; } //we creating the necessary URL string: string ozSURL = "http://127.0.0.1"; //where Ozeki NG SMS Gateway is running string ozSPort = "9501"; //port number where Ozeki NG SMS Gateway is listening string ozUser = HttpUtility.UrlEncode("admin"); //username for successful login string ozPassw = HttpUtility.UrlEncode("abc123"); //user's password string ozMessageType = "SMS:TEXT"; //type of message string ozRecipients = HttpUtility.UrlEncode( textboxRecipient.Text); //who will //get the message string ozMessageData = HttpUtility.UrlEncode(textboxMessage.Text); //body of //message string createdURL = ozSURL + ":" + ozSPort + "/httpapi" + "?action=sendMessage" + "&username=" + ozUser + "&password=" + ozPassw + "&messageType=" + ozMessageType + "&recipient=" + ozRecipients + "&messageData=" + ozMessageData; try { //Create the request and send data to Ozeki NG SMS Gateway Server by HTTP connection HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(createdURL); //Get response from Ozeki NG SMS Gateway Server and read the answer HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse(); System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream()); string responseString = respStreamReader.ReadToEnd(); respStreamReader.Close(); myResp.Close(); //inform the user string result = Regex.Replace(responseString, @"<[^>]*>", string.Empty); textboxError.Text = Server.HtmlEncode( result); textboxError.Visible = true; } catch (Exception) { //if sending request or getting response is not successful Ozeki NG SMS Gateway Server may do not run textboxError.Text = "Ozeki NG SMS Gateway Server is not running!"; textboxError.Visible = true; } }

After I run I got text as <strong>xml doc</strong> like this

<Responses> <Response0> <Action>sendMessage</Action> <Data> <AcceptReport> <StatusCode>0</StatusCode> <StatusText>Message accepted for delivery</StatusText> <MessageID>89c8011c-e291-44c3-ac72-cd35c76cb29d</MessageID> <Recipient>+85568922903</Recipient> </AcceptReport> </Data> </Response0> </Responses>

but I want it diplay as

Message accepted for delivery Message ID: IEUHSHIL Recipient: +441234567

So how can I do this?

Answer1:

you got a json result :

You converted it into string and then replaced braces with spaces , Thats why you got xml.

Recheck these lines :

//inform the user string result = Regex.Replace(responseString, @"<[^>]*>", string.Empty); textboxError.Text = Server.HtmlEncode( result);

Check ResponseString and extract the required data from it.

Helpful links : <a href="https://stackoverflow.com/questions/5493949/reading-httpwebresponse-json-response-c-sharp" rel="nofollow">reading HttpwebResponse json response, C#</a> , <a href="https://stackoverflow.com/questions/9197963/how-to-split-json-format-string-in-order-to-deserialize-is-into-net-object" rel="nofollow">how to split json format string in order to Deserialize is into .net object?</a>

Answer2:

with regards to one of the suggested methods in the comments, use something like this;

XmlDocument doc = new XmlDocument(); doc.LoadXml(load your xml document or string here); XmlNodeList xnList = doc.SelectNodes("Response0/Data/AcceptReport"); foreach (XmlNode xn in xnList) { string status = xn["StatusTest"].InnerText; string messageID = xn["MessageID"].InnerText; string recipient = xn["Recipient"].InnerText; } string finalString = string.Format("{0} Message ID: {1} Recipient {2}", status, messageID, recipient);

This will create an XML document based on the document or string you load into it. XmlNodeList allows you to basically pick out any XmlElements that you want, and in this case you format a string with the node information, in the format that you requested

Answer3:

Try something like this

string stext = @"<Responses> <Response0> <Action>sendMessage</Action> <Data> <AcceptReport> <StatusCode>0</StatusCode> <StatusText>Message accepted for delivery</StatusText> <MessageID>89c8011c-e291-44c3-ac72-cd35c76cb29d</MessageID> <Recipient>+85568922903</Recipient> </AcceptReport> </Data> </Response0> </Responses>"; XElement xm = XElement.Parse(stext); string sout=""; sout = xm.Descendants("StatusText").First().Value + " Message ID:" + xm.Descendants("MessageID").First().Value + " Recipient:" + xm.Descendants("Recipient").First().Value;

Answer4:

How about using XmlDocument class with XPath?

Client code:

XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(...); // Load from file, stream, etc. string status = GetDeliveryStatus(xmlDocument);

XML document processing:

private static string GetDeliveryStatus(XmlDocument xmlDocument) { XmlNode reportNode = xmlDocument.SelectSingleNode("/Responses/Response0/Data/AcceptReport"); if (reportNode == null) throw new ArgumentException("AcceptReport node is absent", xmlDocument); var messageIDNode = reportNode["MessageID"]; if (messageIDNode == null) throw new ArgumentException("MessageID node is absent", xmlDocument); var messageID = messageIDNode.InnerText; var recipientNode = reportNode["Recipient"]; if (recipientNode == null) throw new ArgumentException("Recipient node is absent", xmlDocument); var recipient = recipientNode.InnerText; var result = string.Format("Message accepted for delivery Message ID: {0} Recipient: {1}", messageID, recipient); return result; }

Answer5:

Use XSLT. The reason is that it makes it easy to store the transform in a file. This means if the message format ever changes, it is easy to update your transform to cope.

Add a function like

public void XslTransformer(string source, string stylesheet, string output) { XslTransform xslt = new XslTransform(); xslt.Load(stylesheet); xslt.Transform(source, output); }

And call it, passing your XML, and a transform like:

<?xml version="1.0" encoding="ISO-8859-1"?> <!-- Edited by XMLSpy® --> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> Message accepted for delivery <table border="0"> <tr> <td>Message ID:</td> <td><xsl:value-of select="Responses/Response0/Data/AcceptReport/MessageID"/></td> <td>Recipient:</td> <td><xsl:value-of select="Responses/Response0/Data/AcceptReport/Recipient"/></td> <td>StatusCode:</td> <td><xsl:value-of select="Responses/Response0/Data/AcceptReport/MessageID"/></td> </tr> </table> </html> </xsl:template> </xsl:stylesheet>

Change this format as you like.

Recommend

  • Getting JSON Object from MVC Controller
  • How to call/execute another ASP.net page from the parent ASP.Net page without disrupting the flow of
  • Using HttpWebRequest, Keep-alive not working for many similar requests to localhost
  • Removing a particular header item in HTTP web requests
  • How to send SMS to different Phone number
  • HttpWebResonse hangs on multiple request
  • Application hangs on GetRequestStream() after first request
  • Forcing C#'s HTTP Response to Return a Status Code Instead of a Description
  • HttpWebRequest redirect with cookies
  • Google Chrome Plugin development - Monitor network requests?
  • How would I programatically login to a site such as codeproject or stackoverflow, using WebClient?
  • GCM push notification with C# asp.net giving null as notification in android devices
  • Task event or action on cancel token requested
  • How do I connect to the Asana Rest API using c#?
  • Selenium ChromeDriver (C#) Crashes Only in Visual Studio Debug Mode
  • .Net Compact Framework 3.5 HTTP POST
  • receiving X509 client certificates in web requests
  • Conversion of VB6 HTTP request to VB.Net 2.0
  • How to Save JSON data to SQL server database in C#?
  • what makes a request a new request in asp.net C#
  • converting text file into xml using php?
  • Check for zero lines output from command over SSH
  • nonblocking BIO_do_connect blocked when there is no internet connected
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • SignalR .NET Client Invoke throws an exception
  • How to add date and time under each post in guestbook in google app engine
  • Display Images one by one with next and previous functionality
  • Jquery - Jquery Wysiwyg return html as a string
  • Return words with double consecutive letters
  • Arrays break string types in Julia
  • Is there a mandatory requirement to switch app.yaml?
  • File upload with ng-file-upload throwing error
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • InvalidAuthenticityToken between subdomains when logging in with Rails app
  • SQL merge duplicate rows and join values that are different
  • AngularJs get employee from factory
  • WPF Applying a trigger on binding failure
  • Java static initializers and reflection
  • LevelDB C iterator
  • Can't mass-assign protected attributes when import data from csv file