Wednesday, 30 December 2015

XML : Building XML request with RestSharp

I am attempting to work with a REST API using RestSharp and C#. The documentation for the API that I am using gives a sample XML request:

  <?xml version='1.0' encoding='UTF-8'?>    <messages>     <accountreference>EX0000000</accountreference>    <from>07700900654</from>   <message>      <to>07700900123</to>      <type>SMS</type>      <body>Hello Mr Sands.</body>   </message>     <message>      <to>07700900124</to>      <type>SMS</type>      <body>Hello Mr Mayo.</body>   </message>    </messages>    

I am struggling to understand how to build the request in the format that they want (multiple elements called "message")

I have created these classes for RestSharp to serialize:

  public class messages  {      public string accountreference { get; set; }        public string from { get; set; }        public message message { get; set; }  }    public class message  {      public string to { get; set; }        public string body { get; set; }  }    

And here is my RestSharp code:

  var client = new RestClient("http://api.url.com/v1.0")                           {                               Authenticator =                                   new HttpBasicAuthenticator(                                   UserName,                                   Password)                           };    var request = new RestRequest("theresource", Method.POST) { RequestFormat = DataFormat.Xml };    request.AddBody(      new messages          {              accountreference = Configuration.AccountReference,              from = Configuration.From,              message =                  new message { to = Configuration.Message.To, body = Configuration.Message.Body }          });    var response = client.Execute(request);    

This works great when I have only 1 message element, but I don't know how to create multiple message elements without having them nested in an array, which doesn't work with the API.

No comments:

Post a Comment