How to create XML file dynamically in c#.net?
How to create XML file dynamically in c#.net?
In this article we will learn , How to create dynamic file in c#.net using ASP.NET CORE C#Step 1: Let's create a solution to implement How to create XML file dynamically in c#.net?
File -> New -> Project -> ASP.NET Core Web Application -> Next -> Enter file name and click create
Step 2: Create a new action method in Home controller and create a view and add below html code in view
@{
ViewData["Title"] = "Generate XML File";
}
@ViewData["Title"]
@{
ViewData["Title"] = "Generate XML File";
}
@ViewData["Title"]
Step 3: Create a new action like below and have a look on below Code
[HttpPost]
public IActionResult GenerateXMLFile(string action)
{
if (!string.IsNullOrEmpty(action))
{
string xmlData = generateFile();
string xmlString = xmlData;
string fileName = "SampleFile.xml";
var stream = new MemoryStream();
var writer = XmlWriter.Create(stream);
writer.WriteRaw(xmlString);
stream.Position = 0;
var fileStreamResult = File(stream, "application/xml", fileName);
return fileStreamResult;
}
return null;
}
SqlConnection connetDb()
{
string connetionString = @"Data Source=*****;database=blog; Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
SqlConnection sqlConnection = new SqlConnection(connetionString);
return sqlConnection;
}
DataSet getData()
{
var sqlconnection = this.connetDb();
string command = "SELECT [OrderDate] ,[Region] ,[Rep] ,[Item] ,[Units] ,[UnitCost] ," +
"[Total] FROM [salesOrder] order by [OrderDate]";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(command, sqlconnection);
DataSet dataSet = new DataSet("data");
sqlDataAdapter.Fill(dataSet);
return dataSet;
}
private string generateFile()
{
var xmlData = this.getData().GetXml();
return xmlData;
}
Step 4: Hit F5 and click on Generate XML File as show in below Image
You will get a popup to save the file or it will directly download based on your browser setting
With ❤️ Happy Coding
Ref link
https://github.com/coremicroservices/How-to-create-XML-file-dynamically-in-c-.net
https://github.com/coremicroservices/How-to-create-XML-file-dynamically-in-c-.net
Comments
Post a Comment