Parsing XML with namespaces in SQL Server

痴心易碎 提交于 2019-12-05 04:48:11

问题


I am having a hard time trying to parse an XML that has some namespaces defined:

<TravelItineraryReadRS xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Version="2.2.0">    
<TravelItinerary xmlns="http://webservices.sabre.com/sabreXML/2011/10">
<CustomerInfo>          
<PersonName WithInfant="false" NameNumber="01.01" RPH="1">              
<GivenName>JEFF S</GivenName>"

The XMl is stored in an XML type column named response, and I want to get the GivenName value, for which I use the below query:

;WITH XMLNAMESPACES (DEFAULT 'http://webservices.sabre.com/sabreXML/2011/10')
select 
response.value('(/TravelItineraryReadRS/TravelItinerary/CustomerInfo/PersonName[1]/GivenName)[1]', 'nvarchar(50)') AS Name
from dbo.RezMonitorXMLdataTest where locator = 'GUBXRV'

but instead of getting JEFF S as a result I get NULL. I think this might be related to the namespaces used. Does anyone know how could I get the GivenName value?

Thanks in advance,

Guzmán


回答1:


Since your top-level node <TravelItineraryReadRS> is not part of that XML namespace, you cannot use the DEFAULT qualifier. Instead, you have to define a XML namespace prefix, and include that in your XQuery:

;WITH XMLNAMESPACES ('http://webservices.sabre.com/sabreXML/2011/10' AS ns)
SELECT
    XmLContent.value('(/TravelItineraryReadRS/ns:TravelItinerary/ns:CustomerInfo/ns:PersonName[1]/ns:GivenName)[1]', 'nvarchar(50)') AS Name
FROM 
    dbo.RezMonitorXMLdataTest 
WHERE
    locator = 'GUBXRV'


来源:https://stackoverflow.com/questions/18192022/parsing-xml-with-namespaces-in-sql-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!