【问题标题】:T-SQL Read xml file with namespacesT-SQL 读取带有命名空间的 xml 文件
【发布时间】:2018-05-15 18:18:30
【问题描述】:

我尝试在 sql server 中读取 xml 文件:

DECLARE @XMLToParse  XML 

-- Load the XML data in to a variable to work with.
-- This would typically be passed as a parameter to a stored proc
SET @XMLToParse = '<Response xmlns="http://tempuri.org/">
    <AuthResult xmlns:a="http://schemas.datacontract.org/2004/07/Sistema.Soap.Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <a:Result>
            <a:Id_Value>500</a:Id_Value>
        </a:Result>
        <a:Result>
            <a:Id_Value>895</a:Id_Value>
        </a:Result>
    </AuthResult>
</Response>'

-- Declare temp table to parse data into
DECLARE @ParsingTable  TABLE
    (Id_Value   INT)

-- Parse the XML in to the temp table declared above
INSERT
INTO    @ParsingTable
    (Id_Value)
SELECT  xmlData.A.value('.', 'INT') AS Id_Value
FROM    @XMLToParse.nodes('Response/AuthResult/Result') xmlData(A)

-- Insert into the actual table from the temp table

SELECT  Id_Value
FROM    @ParsingTable

显然代码是正确的,但我无法获取值,我哪里错了?

【问题讨论】:

    标签: sql xml namespaces


    【解决方案1】:

    使用WITH XMLNAMESPACES 声明命名空间,并对不在默认命名空间中的节点使用相应的前缀。

    ...
    
    -- Parse the XML in to the temp table declared above
    ;WITH XMLNAMESPACES (DEFAULT 'http://tempuri.org/',
                         'http://schemas.datacontract.org/2004/07/Sistema.Soap.Contracts' as a,
                         'http://www.w3.org/2001/XMLSchema-instance' as i
                         )
    INSERT
    INTO    @ParsingTable
        (Id_Value)
    SELECT  xmlData.A.value('.', 'INT') AS Id_Value
    FROM    @XMLToParse.nodes('Response/AuthResult/a:Result') xmlData(A)
    
    ...
    

    【讨论】:

    • 好的答案(我这边+1),但我建议不要使用.value('.', 'INT'),而是使用(a:Id_Value/text())[1] 作为XPath。这更快并且 - 如果可能有其他节点 - 更安全。
    猜你喜欢
    • 2012-02-13
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多