I am working on a project which needs to generate xml file of database table with all rows and columns. For that I think I need to query database table and What should I do I have no idea. I am working with asp.net core 2 for backend api part and angular in frontend part. I need to return response in JSON but data should be xml like. How can I do that? I am out of logical and technical(coding) help. Please recommend any code. Also I have some nullable attributes in my database. How do I tackle that problem?
Asked
Active
Viewed 650 times
-1
-
XML and JSON are both data serialization formats. But they are very different. I'm not sure what you mean by *"response in JSON but data should be xml like"*. If it's in JSON, it isn't XML. As a hint, read all of your data into a collection of objects whose properties are named like your table's columns and which are type compatible (perhaps using Dapper). Then serialize the collection to either XML or JSON. Once you get code like that, come back and ask a question if you run into an issue or issues. – Flydog57 Jul 11 '19 at 04:38
-
Have you see this link: https://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome. I think it will help to get a solution. – priyanka Jul 11 '19 at 05:48
1 Answers
1
You could refer to demo below which retrieve the data in a table and save to XML file.
1.Assume I have an Employee
Model, and map the Employees
table in database
public class Employee
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime DateWhenJoined { get; set; }
}
//In ApplicationDbContext
public DbSet<Employee> Employees { get; set; }
2.Controller:
public class EmployeesController : Controller
{
private readonly ApplicationDbContext _context;
public EmployeesController(ApplicationDbContext context)
{
_context = context;
}
public void DownloadToXML()
{
List<Employee> emList = _context.Employees.ToList();
if (emList.Count > 0)
{
var xEle = new XElement("Employees",
from emp in emList
select new XElement("Employee",
new XElement("EmployeeID", emp.Id),
new XElement("CompanyName", emp.Name),
new XElement("DateOfBirth", emp.DateOfBirth),
new XElement("DateWhenJoined", emp.DateWhenJoined)
));
xEle.Save("test.xml");
}
}
}
3.Call the action and it will generate test.xml file in your root.
<? xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee>
<EmployeeID>1</EmployeeID>
<CompanyName>Alex</CompanyName>
<DateOfBirth>2019-05-11T03:33:00</DateOfBirth>
<DateWhenJoined>2019-05-12T03:03:00</DateWhenJoined>
</Employee>
<Employee>
<EmployeeID>2</EmployeeID>
<CompanyName>Bob</CompanyName>
<DateOfBirth>0001-01-01T00:00:00</DateOfBirth>
<DateWhenJoined>2019-05-20T00:00:00</DateWhenJoined>
</Employee>
</Employees>

Ryan
- 19,118
- 10
- 37
- 53