简体   繁体   中英

translate xml file to text

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

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

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;

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

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 : reading HttpwebResponse json response, C# , how to split json format string in order to Deserialize is into .net object?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM