在不事先了解架构的情况下解析XML的更好方法

时间:2013-10-18 17:47:59

标签: sql xml tsql sql-server-2005 xml-parsing

使用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;

这有效,但它很丑陋而且没有基础设置。必须有更好的方法。

EDIT。在我的情况下,架构将始终是

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

1 个答案:

答案 0 :(得分:6)

你走了:

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)