Convert Web service/ Web API XML string into data table in C# | Part 6

preview_player
Показать описание
Convert Web service/ Web API XML string into data table in C# :
static void Main(string[] args)
{

// Example URL for the WCF RESTful service

// Create a new HttpClient instance
using (HttpClient client = new HttpClient())
{
// Send a synchronous GET request
HttpResponseMessage response = client.GetAsync(url).Result;

// Ensure we get a successful response
response.EnsureSuccessStatusCode();

// Read and return the response content
string responseBody = response.Content.ReadAsStringAsync().Result;

// Create a new DataSet
DataSet dataSet = new DataSet();

// Load the XML string into the DataSet
using (StringReader stringReader = new StringReader(responseBody))
{
dataSet.ReadXml(stringReader);
}

// Extract a specific DataTable from the DataSet
DataTable dataTable = dataSet.Tables["employee"];

//now save the data table value in databse
// Create a new SqlConnection
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HSSNFCU;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=1234");

con.Open();

// Create a SqlBulkCopy instance
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
{
// Set the destination table name
bulkCopy.DestinationTableName = "destination_Employee";

// Optional: Map columns if the DataTable column names differ from the destination table
bulkCopy.ColumnMappings.Add("empid", "empid");
bulkCopy.ColumnMappings.Add("emp_name", "emp_name");
bulkCopy.ColumnMappings.Add("salary", "salary");
bulkCopy.ColumnMappings.Add("emp_city", "emp_city");

// Write data to the database
bulkCopy.WriteToServer(dataTable);
}
con.Close();

}
}
Note: HttpClient is a class in C# designed to send HTTP requests and receive HTTP responses from a resource identified by a URI.
Рекомендации по теме