2013-10-18 39 views
0

使用SQL Server 2005我需要解析XML中的所有值,而不必事先知道元素名稱。更好的方法來解析XML而不知道模式事先

以下是我有:

declare @xml xml 

--REMEMBER THIS XML COULD CONTAIN ANYTHING. THIS IS AN EXAMPLE 
set @xml = ' 
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <id>1</id> 
    <name>asdf</name> 
    <siteaddress1>asdf</siteaddress1> 
    <siteaddress2>asdf</siteaddress2> 
    <sitecity>asdf</sitecity> 
    <sitestateid>4</sitestateid> 
    <sitezip>333333</sitezip> 
    <phone>asdfsadf</phone> 
    <epaid>34343</epaid> 
</row>' 

declare @rows int 
declare @i int 
declare @sql nvarchar(max) 

set @i = 0 
set @rows = (SELECT Tbl.Col.value('count(*)', 'int') FROM @xml.nodes('//row') Tbl(Col)) 
set @sql = '' 

while (@i <= @rows) 
begin 
    set @i = @i + 1 
    set @sql = @sql + 'select Tbl.Col.value(''*[' + cast(@i as varchar(10)) + ']'', ''varchar(max)'') 
         FROM @x.nodes(''//row'') Tbl(Col) 
         union ' 
end 

set @sql = substring(@sql,0,len(@sql)-5) 

exec sp_executesql @sql,N'@x xml', @x = @xml; 

這工作,但它的醜陋,而不是基於集。一定有更好的方法。

編輯。在我的情況的模式永遠是

<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
... 
... 
... 
</row> 
+0

XML和SQL(尤其是sql server 2005)不能很好地協同工作。另外,考慮到XML可以兩肋插刀*,如果你有一個像模式?你的模式至少有點靜態? –

+0

@N West。請參閱我的編輯。 – Coltech

回答

5

在這裏你去:

DECLARE @xml XML 

set @xml = ' 
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <id>1</id> 
    <name>asdf</name> 
    <siteaddress1>asdf</siteaddress1> 
    <siteaddress2>asdf</siteaddress2> 
    <sitecity>asdf</sitecity> 
    <sitestateid>4</sitestateid> 
    <sitezip>333333</sitezip> 
    <phone>asdfsadf</phone> 
    <epaid>34343</epaid> 
</row>' 

select r.value('fn:local-name(.)', 'nvarchar(50)') as 'elementName', 
    r.value('.','nvarchar(max)') AS 'value' 
FROM 
    @xml.nodes('//row/*') AS records(r) 

如果你只是想在不同的元素名稱,你只需要做:

select distinct r.value('fn:local-name(.)', 'nvarchar(50)') as t FROM 
    @xml.nodes('//row/*') AS records(r) 
+0

輝煌。謝謝! – Coltech

+0

這適用於元素,如何提取屬性值? – Abe

相關問題