从 SQL 中的 XML 对象获取命名空间

问题描述

考虑以下 XML

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none" s:mustUnderstand="1">http://xmlns.scania.com/management/messages/v3</Action>
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Data xmlns="http://xmlns.scania.com/management/schema/messages/v3">
      <Details />
    </Data>
  </s:Body>
</s:Envelope>

我正在尝试在信封下获取标记的 xmlns 值中的命名空间值。 我尝试使用

XMLObject.value('namespace-uri((/*:Envelope)[1])','varchar(100)') 这将返回第一个元素的 xmlns。即"http://schemas.xmlsoap.org/soap/envelope/"

我需要深入到标签的 xmlns。即"http://xmlns.scania.com/management/schema/messages/v3"

有人可以帮我吗?

解决方法

以下是选择命名空间 URI 的三种方法...

declare @xml xml = N'<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header>
    <Action xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none" s:mustUnderstand="1">http://xmlns.scania.com/management/messages/v3</Action>
  </s:Header>
  <s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Data xmlns="http://xmlns.scania.com/management/schema/messages/v3">
      <Details />
    </Data>
  </s:Body>
</s:Envelope>';

-- Avoid this: wildcard namespaces are slow...
select Envelope.value('namespace-uri(.)','nvarchar(max)') as NamespaceUri
from @xml.nodes('/*:Envelope/*:Body/*:Data') soap(Envelope);

-- Declare namespace(s) inside the XPath expression...
select Envelope.value('namespace-uri(.)','nvarchar(max)') as NamespaceUri
from @xml.nodes('declare namespace soap="http://schemas.xmlsoap.org/soap/envelope/";
/soap:Envelope/soap:Body/*:Data') soap(Envelope);

-- Declare namespace(s) before the query (these would be usable in FOR XML as well)...
with xmlnamespaces(
  'http://schemas.xmlsoap.org/soap/envelope/' as soap
)
select Envelope.value('namespace-uri(.)','nvarchar(max)') as NamespaceUri
from @xml.nodes('/soap:Envelope/soap:Body/*:Data') soap(Envelope);

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...