How to create XML file dynamically in c#.net?

How to disable table row in Angular ? , ANGULAR WITH CORE .NET AND MVC RAZOR ENGINE

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

<br /> @{<br /> ViewData["Title"] = "Generate XML File";<br /> }<br /> <h1>@ViewData["Title"]</h1><br /> <form asp-action="GenerateXMLFile" asp-controller="Home" method="post"><br /> We will use this page to generate XML file.<br /> <br /> <input name="action" placeholder="Generate XML File" title="Generate XML File" type="submit" value="Generate XML File" /><br /> </form>

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


Comments

Popular posts from this blog

How to disable table row in Angular

How to get Array value in Angular ?