首页 > 解决方案 > 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?

标签: c#xml-serializationasp.net-core-2.0

解决方案


您可以参考下面的演示,它检索表中的数据并保存到 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>

请参阅https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/xdocument-class-overview


推荐阅读