在asp.net c#中将数据库导出到xml文件

时间:2016-02-23 12:35:54

标签: c# sql xml asp-classic

在将所有表从sql数据库导出到xml时,表名节点被命名为table,table1,table2等。如何在导出到xml文件时获取与数据库完全相同的表名?

3 个答案:

答案 0 :(得分:1)

不确定如何导出,如果使用DataSet导出,则必须没有DataSet中每个表的表名,请确保数据集中的表具有名称。

        DataSet ds = new DataSet();
        foreach (DataTable d in ds.Tables)
        {
            d.TableName = "TableName";
        }
        ds.WriteXml("filepath");
        //Or
        DataTable dt = new DataTable("TableName");
        dt.WriteXml("filepath");

答案 1 :(得分:0)

如果使用asp,则需要xdocument,xelement,xdocumenttype,xattribute,XDeclaration

 XDocument XMLDocument=new XDocument();
    XDeclaration Declaration=new XDeclaration("1.0", "utf-8", "yes");
    XDocumentType doctype = new XDocumentType("filename", "", "",null);
    XMLDocument.AddFirst(doctype);
    XMLDocument.Declaration=Declaration;

答案 2 :(得分:0)

欢迎来到Stackoverflow。

我在其中一个项目中也遇到了同样的问题。作为替代方案,我编写了查询以在我的列中检索XML,并将从此列检索到的数据写入我的文件。

查询示例如下;

SELECT (
  SELECT TOP 1 NULL as N,
    (SELECT Employee.EmployeeId as Id, Employee.FirstName as Name,
      (SELECT TOP 1 NULL as N,
        (SELECT Customer.CustomerID as Id, CustomerName as Name
         FROM EmployeesCustomers INNER JOIN Customers Customer
         ON EmployeesCustomers.CustomerID = Customer.CustomerID
         WHERE EmployeesCustomers.EmployeeId = Employee.EmployeeId
         ORDER BY Customer.CustomerID
         FOR XML AUTO, TYPE)
       FROM Customers
       FOR XML AUTO, TYPE)
     FROM EmployeesCustomers INNER JOIN Employees Employee
     ON EmployeesCustomers.EmployeeID = Employee.EmployeeID
     GROUP BY Employee.EmployeeId, Employee.FirstName
     ORDER BY Employee.EmployeeId
     FOR XML AUTO, TYPE)
  FROM Employees
  FOR XML AUTO, ROOT('Company')
) AS COL_XML

完整的详细信息可在以下链接中找到(即使该链接适用于SSIS,该概念适用于所有情况) Click here

如果您有一个非常复杂的查询并且无法根据需要获取输出,您可以继续使用Siva Kumar Siddam建议的方法来为您的数据集提供表格的名称。

希望这有帮助