在SQL Server 2008 R2中存储XML文件

时间:2014-06-03 15:06:58

标签: c# xml xml-serialization sql-server-2008r2-express

我正在尝试将XML数据存储到SQL Server 2008 R2 Express数据库中,每个xml文件都有不同的数据。最简单的方法是什么?

最佳选择是什么,请以示例解释。

2 个答案:

答案 0 :(得分:2)

我认为最简单的方法是创建一个存储过程来为您处理存储。然后,您可以通过ORM of preferage检索它,并让C#为您反序列化。

CREATE TABLE [dbo].[MyXmlStorage] 
( 
    [Id] [int] IDENTITY(1,1) NOT NULL, 
    [FileName] [nvarchar](255) NOT NULL, 
    [Xml] [xml] NOT NULL, 

    CONSTRAINT [PK_MyXmlStorage] 
    PRIMARY KEY CLUSTERED  ([Id] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

CREATE PROCEDURE [dbo].[InsertXml]
    (@filePathFull nvarchar(255)) 
AS 
   DECLARE @xmlAsString VARCHAR(MAX) 
   DECLARE @sql nvarchar(max) 
   DECLARE @xml XML 
   DECLARE @Rms_FileId nvarchar(50) 
   DECLARE @Rms_Id nvarchar(50) 
   DECLARE @Rms_Type nvarchar(50) 
   DECLARE @Rms_Timestamp nvarchar(50) 

BEGIN 
    SET @sql = 'SELECT @xmlAsString = x.y FROM OPENROWSET( BULK ''' + RTRIM(@filePathFull) + ''', SINGLE_CLOB) x(y)' 
    exec sp_executesql @sql,N'@xmlAsString VARCHAR(MAX) OUTPUT',@xmlAsString OUTPUT 

    set @xml = CONVERT(XML,@xmlAsString)  

    INSERT INTO MyXmlStorage([FileName],[Xml]) 
    VALUES (@filePathFull, @xml) 
END 

然后像这样运行:

exec InsertXml N'C:\files\xmlfile.xml'

答案 1 :(得分:1)

好的,这是一个将xml的值存储到表中的示例。我还没有尝试过这段代码,但它应该有效,但至少它应该说明如何按预期执行。

   /* Imagine your xml looks something like this

    <Content>
        <Title>Text</Title>
        <Value>15</Value>
    </Content>
    */

    CREATE TABLE [dbo].[MyXmlStorage] 
    ( 
        [Id] [int] IDENTITY(1,1) NOT NULL, 
        [Title] [nvarchar](100) NOT NULL, 
        [Value] int NOT NULL,

        CONSTRAINT [PK_MyXmlStorage] 
        PRIMARY KEY CLUSTERED  ([Id] ASC)
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] 

    CREATE PROCEDURE [dbo].[InsertXml]
        (@filePathFull nvarchar(255)) 
    AS 
       DECLARE @xmlAsString VARCHAR(MAX) 
       DECLARE @sql nvarchar(max) 
       DECLARE @xml XML 
       DECLARE @Rms_FileId nvarchar(50) 
       DECLARE @Rms_Id nvarchar(50) 
       DECLARE @Rms_Type nvarchar(50) 
       DECLARE @Rms_Timestamp nvarchar(50) 

    BEGIN 
        SET @sql = 'SELECT @xmlAsString = x.y FROM OPENROWSET( BULK ''' + RTRIM(@filePathFull) + ''', SINGLE_CLOB) x(y)' 
        exec sp_executesql @sql,N'@xmlAsString VARCHAR(MAX) OUTPUT',@xmlAsString OUTPUT 

        set @xml = CONVERT(XML,@xmlAsString)  

        /* Use xpath to query nodes for values inside the Content tag*/
        INSERT INTO MyXmlStorage([Title],[Value]) 
        SELECT 
            x.y.value('title[1]/text()[1]', 'nvarchar(100)') AS title,
            x.y.value('value[1]/text()[1]', 'int') AS value
        FROM @xml.nodes('//Content') AS x(y)
    END 
)