简体   繁体   中英

Output Linq Query Result to XML

In the SQL Server Management studio, I can do this:

SELECT * FROM tableName FOR XML RAW

to produce a list of XML entries for the data in my table.

How do I do it in C# using LINQ queries?

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.

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:

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; 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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