简体   繁体   中英

SQL Server : select from xml with namespace

I have code like below:

declare @strXML nvarchar(max) =
'<?xml version="1.0" encoding="utf-16"?>
    <GetDictResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <GetDictResult>
    <Success xmlns="http://or.org/ValidationSchema.xsd">true</Success>
    <Dicts xmlns="http://or.org/ValidationSchema.xsd">
      <Dict>
        <Code>TADR</Code>
        <Name>Type of address</Name>
      </Dict>
    </Dicts>
  </GetDictResult>
</GetDictResponse>
'

declare @xml xml =  CONVERT(XML,CONVERT(NVARCHAR(MAX),@strXML))

--empty row result
SELECT
    ltrim(rtrim(T.c.value('Code[1]','VARCHAR(max)'))) Code,
    ltrim(rtrim(T.c.value('Name[1]','VARCHAR(max)'))) Name
FROM @xml.nodes('*/*/*/*') AS T(C)
--any rows
SELECT
    ltrim(rtrim(T.c.value('Code[1]','VARCHAR(max)'))) Code,
    ltrim(rtrim(T.c.value('Name[1]','VARCHAR(max)'))) Name
FROM @xml.nodes('GetDictResponse/GetDictResult/Dicts/Dict') AS T(C)

How may I get Code and Name values?

Regards, RB

Try this:

DECLARE @strXML XML =
'<GetDictResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <GetDictResult>
        <Success xmlns="http://or.org/ValidationSchema.xsd">true</Success>
        <Dicts xmlns="http://or.org/ValidationSchema.xsd">
        <Dict>
        <Code>TADR</Code>
        <Name>Type of address</Name>
      </Dict>
    </Dicts>
  </GetDictResult>
</GetDictResponse>'

;WITH XMLNAMESPACES('http://or.org/ValidationSchema.xsd' as ns)
    SELECT
        Code = c.value('ns:Code[1]', 'NVARCHAR(20)'),
        Name = c.value('ns:Name[1]', 'NVARCHAR(20)')
    FROM 
        @strXml.nodes('/GetDictResponse/GetDictResult/ns:Dicts/ns:Dict') AS T(C)

One problem is the XML header you have - can you get rid of that? Without it, this code does return the desired values:

在此输入图像描述

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