简体   繁体   English

将Linq查询结果输出到XML

[英]Output Linq Query Result to XML

In the SQL Server Management studio, I can do this: 在SQL Server Management Studio中,我可以这样做:

SELECT * FROM tableName FOR XML RAW

to produce a list of XML entries for the data in my table. 为我的表中的数据生成XML条目的列表。

How do I do it in C# using LINQ queries? 如何使用LINQ查询在C#中做到这一点?

var itemCollection = from entry in dataContextTableName select entry for xml raw

doesn't work (it doesn't compile). 不起作用(不编译)。 Any ideas? 有任何想法吗?

You could write a stored procedure, return the XML as an OUTPUT parameter and access that through the LinqToSql DataContext. 您可以编写一个存储过程,将XML作为OUTPUT参数返回,并通过LinqToSql DataContext访问它。

For example: 例如:

CREATE PROCEDURE dbo.GenerateXML

    (
        @xmlOutput nvarchar(MAX) OUTPUT
    )

AS
BEGIN

    SET @xmlOutput  = ( 
        SELECT * FROM tableName FOR XML RAW
    )

END

From here you'd have to drag and drop the stored procedure onto your DBML file using Server Explorer, then in code it's simply: 在这里,您必须使用服务器资源管理器将存储过程拖放到DBML文件上,然后在代码中简单地说:

string xml = "";    
dataContext.GenerateXML(ref xml)

The source on this can be found here 来源可以在这里找到

As James said, you can't do it using raw LinqToSql syntax; 如James所说,您不能使用原始的LinqToSql语法来完成此操作。 alternatively you could serialize the result you get from a standard Linq query (eg: from entry in dataContextTableName select entry ) into XML in code, see here for a good starting point . 或者,您可以将通过标准Linq查询(例如, from entry in dataContextTableName select entry )获得的结果序列化为代码中的XML,请参见此处以获取一个好的起点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM