2011-11-07 56 views
2

我试图从SQL Server中的SOAP响应中获取“响应”文本,但因为从SQL Server解析错误而无法使用soap:Envelope。在SQL Server中解析SOAP XML

XML parsing error: Reference to undeclared namespace prefix: 'soap'.

我的XML回应如下,并且包含在所谓@xmlOut一个nvarchar:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<soap:Body> 
    <Method1Response xmlns="http://tempuri.org/"> 
    <Method1Result>&lt;Interface&gt;&lt;Col1&gt;#result#&lt;/Col1&gt;&lt;Col2&gt;info&lt;/Col2&gt;&lt;Col3&gt;Record is invalid.&lt;/Col3&gt;&lt;Col4&gt;&lt;/Col4&gt;&lt;/Interface&gt;</Method1Result> 
    </Method1Response> 
</soap:Body> 
</soap:Envelope> 

我试图让Method1Result成一个nvarchar但我真的阅读本XML挣扎。

declare @xDoc as xml 
set @xDoc = cast(@xmlOut as xml) 

declare @hdoc int 
exec sp_xml_preparedocument @hdoc OUTPUT, @xDoc 

select * 
from 
( select * 
    from openxml(@hdoc, '/soap:Envelope/soap:Body/MethodResponse', 1) 
    with (MethodResult nvarchar(max)) 
) as x 

exec sp_xml_removedocument @hdoc 

这是怎么了,我通常读我的XML变量在SQL,但只要我尝试阅读肥皂:信封我得到这个错误:

XML parsing error: Reference to undeclared namespace prefix: 'soap'.

回答

1

如果你使用SQL Server 2005或更高版本你可以这样做。

;with xmlnamespaces('http://schemas.xmlsoap.org/soap/envelope/' as [soap], 
        default 'http://tempuri.org/') 
select T.N.value('.', 'nvarchar(max)') 
from @xDoc.nodes('/soap:Envelope/soap:Body/Method1Response/Method1Result') as T(N) 

或者如果您只希望XML中的Method1Result的值更简单/更快一点。

;with xmlnamespaces('http://schemas.xmlsoap.org/soap/envelope/' as [soap], 
        default 'http://tempuri.org/') 
select @xDoc.value('(/soap:Envelope/soap:Body/Method1Response/Method1Result)[1]', 'nvarchar(max)') 
+0

谢谢。方法1在SQL2008上完美工作。 – Elarys

+0

作为第二个问题,您如何使用上述示例从soap中获取faulttring文本:Fault。 我认为这样做,但它没有返回任何值。 ; with xmlnamespaces('http://schemas.xmlsoap.org/soap/envelope/'as [soap], 默认'http://tempuri.org/') select @ xDoc.value('(/ soap:Envelope/soap:Body/soap:Fault/faultstring)[1]','nvarchar(max)') – Elarys

+0

@Elarys - XML区分大小写。也许它应该是'FaultString'。 –