c# - Generate xml file of database table
问题描述
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?
解决方案
您可以参考下面的演示,它检索表中的数据并保存到 XML 文件。
1.假设我有一个Employee
模型,并映射Employees
数据库中的表
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.控制器:
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.调用该操作,它将在您的根目录中生成 test.xml 文件。
<? 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>
推荐阅读
- python - 检查点是否在旋转的矩形内
- javascript - 如何在 useEffect() 之外调用函数
- mysql - 案例陈述中的计数和总和
- machine-learning - 具有自定义成本和梯度函数的 Microsoft.ML 梯度下降
- python - 'user' 不是 DJANGO 中的注册命名空间错误
- networking - 如何在 Google Cloud Platform 实例中为特定 URL/IP 允许特定端口
- c# - 为什么这个 C# 键盘记录器会选择性地保存击键?
- python-3.x - 如何避免python中的嵌套数组if语句
- javascript - 使用事件来反应钩子的状态以针对特定的 div
- swift - 如何制作突出显示的 UIBarButtonItem?