使用 SQL Server 2005,我需要在事先不知道元素名称的情况下解析 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>