首页 > 解决方案 > 使用 LINQ 的 SQL 到 XML

问题描述

我正在尝试从 SQL 数据库中提取并生成格式化的 XML 文件。查看以前的问题,最好的方法是使用 LINQ。

到目前为止,我已将 SQL 数据拉回 C# DataSet,有两个表。我正在使用以下代码尝试输出到 XML 文档

        XDocument doc = new XDocument(
            new XDeclaration("1.0", "UTF-8", "yes"),
            new XElement("Snapshot",
                new XAttribute("Date", "2018-06-04"),
            new XElement("Rooms",
                from p in data.Tables[1].AsEnumerable()
                select new XElement("RoomType1",
                    new XAttribute("Rate", p["Rate"]),
                    new XAttribute("Size", p["Size"]),
                    new XAttribute("Other", p["Other"]),
                    )),
             new XElement("Cutomers",
                from p in data.Tables[2].AsEnumerable()
                select new XElement("Customer",
                    new XAttribute("CustomerId", p["CustomerId"]),
                    new XAttribute("Name", p["Name"]),
                    new XAttribute("PhoneNumber", p["PhoneNumber"]),
                    new XAttribute("Email", p["Email"])
                    ))     
doc.Save(@"c:\temp\WholeFile.xml");          

这几乎产生了我正在寻找的内容,但是在我想按 customerId 分组的第二个数据集上,因此 CustomerId 只会显示一次,然后姓名、电话号码和电子邮件都将显示在下面。

我查看了使用 LINQ 进行分组,因为它看起来好像这是我需要做的,但是当我运行下面的代码时,它正确地按 customerId 分组,但 CustomerId 元素仍然显示在每一行数据上。

            var groups = doc.Descendants("Portfolio")
            .GroupBy(x => (string)x.Attribute("PortfolioId"))
            .ToList();

        var newDoc = new XDocument(
            new XElement("Customers",
                from e in doc.Descendants("Customer")
                group e by (string)e.Attribute("CustomerId") into g
                select new XElement("Customer",
                    new XAttribute("CustomerId", g.Key),
                g
                )
            )
        );

几乎尝试了所有方法,但无法弄清楚如何从集合中选择字段(这是正确的术语)“g”。

非常感谢任何帮助!

标签: c#sqlxmllinq

解决方案


我个人发现在 SQL Server 上创建 XML 更容易。以下是我将如何解决这个问题:

USE [yourDB]
GO
/****** Object:  StoredProcedure [dbo].[SP_yourProcedure]    Script Date: today ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      you
-- Create date: today
-- Description: 
-- =============================================
ALTER PROCEDURE [dbo].[SP_yourProcedure] 
    -- Add the parameters for the stored procedure here
    @example1 varchar(50) = '',
    @example2 varchar(50) = '',
    @example3 varchar(50) = '',
    @example4 int = 0
    -- ect

AS  
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Initialize XML
    DECLARE @xml xml = (
    SELECT  

    -- Declare XML Structure
    TA.example1 AS 'example1',
    TA.example2 AS 'example2',
    TA.example3 AS 'example3',
    TA.example4 AS 'example4'
    -- ect

    -- Specify the Context of the XML
    FROM yourTable TA WHERE yourConditionFactor = @yourConditionFactor
    FOR XML PATH('yourXML'))

-- Do what you want with your @xml here
-- enter code



END

我发现定义 XML 结构非常简单和简约。然后,您可以使用 EF 和 LINQ 将存储过程调用到您的 c# 环境中,并将数据参数传递给您的过程。如果您要创建多个 XML,只需让您的 SP 在 foreach 语句中运行。

希望这可以帮助!


推荐阅读