简体   繁体   English

将XML文件插入SQL Server

[英]Insert XML file into SQL Server

I'm trying to import an XML file into a SQL table. 我正在尝试将XML文件导入SQL表。 I found a few examples of code to do this, but I can't seem to get it to work. 我找到了一些代码来做这个,但我似乎无法让它工作。 I've tried a few variations in my code but at this point I'm not sure if the issue is the XML file structure or my SQL. 我在我的代码中尝试了一些变体,但此时我不确定问题是XML文件结构还是我的SQL。

Below is the code I'm using as well as the XML file (truncated to one record). 下面是我正在使用的代码以及XML文件(截断为一个记录)。

CREATE TABLE workspace.dbo.tbt_SED_XMLwithOpenXML
(
Id INT IDENTITY PRIMARY KEY,
XMLData XML,
LoadedDateTime DATETIME
)    

INSERT INTO workspace.dbo.tbt_SED_XMLwithOpenXML(XMLData, LoadedDateTime)
SELECT CONVERT(XML, BulkColumn) AS BulkColumn, GETDATE() 
FROM OPENROWSET(BULK 'File.xml', SINGLE_BLOB) AS x;


DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX)    

SELECT @XML = XMLData FROM workspace.dbo.tbt_SED_XMLwithOpenXML WHERE ID =     '1' -- The row to process    

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML


INSERT INTO workspace.dbo.tb_SED_Emails
SELECT email
FROM OPENXML(@hDoc, 'responseData/manifest/contact_data')
WITH 
(
email [varchar](128) 'email'
)


EXEC sp_xml_removedocument @hDoc
GO

XML File Example: XML文件示例:

<?xml version="1.0" encoding="utf-8"?>
<methodResponse>
<item>
    <methodName>
        <![CDATA[]]>
    </methodName>
    <responseData>
        <manifest>
            <contact_data>
                <email>jason.kang@stanfordalumni.org</email>
            </contact_data>
        </manifest>
    </responseData>
    <responseNum>
        <![CDATA[1]]>
    </responseNum>
    <responseCode>
        <![CDATA[]]>
    </responseCode>
</item>
</methodResponse>

Try to use the built-in, native XQuery support instead of the clunky old OPENXML stuff: 尝试使用内置的本机XQuery支持,而不是使用笨重的旧OPENXML

SELECT
    Email = XC.value('(email)[1]', 'varchar(255)')
FROM 
    workspace.dbo.tbt_SED_XMLwithOpenXML
CROSS APPLY 
    XMLData.nodes('/methodResponse/item/responseData/manifest/contact_data') AS XT(XC)

That should output the desired e-mail address for you: 那应该为您输出所需的电子邮件地址:

You are using the wrong xPath expression. 您正在使用错误的xPath表达式。

Change 'responseData/manifest/contact_data' to 'methodResponse/item/responseData/manifest/contact_data' . 'responseData/manifest/contact_data'更改为'methodResponse/item/responseData/manifest/contact_data'

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

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