Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.5.0+

curl with Variable Substitution in an XML Request Body

See more CURL Examples

This example shows how to use variables inside an XML request body using the {{variable_name}} syntax. When the HTTP request’s Content-Type indicates XML, Chilkat automatically applies proper XML entity encoding to each substituted value, ensuring the resulting XML remains valid.

Chilkat Rust Downloads

Rust

// Variable names are enclosed between {{ and }}

// curl -X POST https://api.example.com/api/orders \
//   -H "Content-Type: application/xml; charset=utf-8" \
//   -H "Accept: application/xml" \
//   -d '<order>
//   <customerName>{{customer_name}}</customerName>
//   <note>{{note}}</note>
//   <address>{{address}}</address>
//   <instructions>{{instructions}}</instructions>
// </order>'

let sb_curl = chilkat::StringBuilder::new();
let _ = sb_curl.append_ln("curl -X POST https://api.example.com/api/orders \\");
let _ = sb_curl.append_ln("  -H \"Content-Type: application/xml; charset=utf-8\" \\");
let _ = sb_curl.append_ln("  -H \"Accept: application/xml\" \\");
let _ = sb_curl.append_ln("  -d '<order>");
let _ = sb_curl.append_ln("  <customerName>{{customer_name}}</customerName>");
let _ = sb_curl.append_ln("  <note>{{note}}</note>");
let _ = sb_curl.append_ln("  <address>{{address}}</address>");
let _ = sb_curl.append_ln("  <instructions>{{instructions}}</instructions>");
let _ = sb_curl.append_ln("</order>'");

let curl = chilkat::HttpCurl::new();

// The values below contain chars that will require XML entity encoding.  
// Chilkat will automatically do the encoding because the Content-Type of this request is "application/xml"
curl.set_var("customer_name", "John & Sons");
curl.set_var("note", "He said \"Ship it ASAP!\"");
curl.set_var("address", "123 <Main> Street");
curl.set_var("instructions", "Use door #2 & call upon arrival");

// To demonstrate how the variables are replaced, this example does not execute the curl command. 
// Instead, it generates the raw HTTP request that would be sent if the curl command were run.
let sb_raw_request = chilkat::StringBuilder::new();
if curl.to_raw_request(&sb_curl.get_as_string().unwrap_or_default(), &sb_raw_request).is_err() {
    println!("{}", curl.last_error_text());
    return;
}

println!("{}", sb_raw_request.get_as_string().unwrap_or_default());

// The output is shown below.
// Notice the chars that were XML entity encoded.

// POST /api/orders HTTP/1.1
// Accept: application/xml
// Host: api.example.com
// Content-Type: application/xml; charset=utf-8
// Content-Length: 229
// 
// <order>
//   <customerName>John &amp; Sons</customerName>
//   <note>He said &quot;Ship it ASAP!&quot;</note>
//   <address>123 &lt;Main&gt; Street</address>
//   <instructions>Use door #2 &amp; call upon arrival</instructions>
// </order>