使用SQL Server解析XML

时间:2013-10-28 13:45:37

标签: sql sql-server xml sql-server-2008

在nvarchar字段Description中,我有以下数据:

<p>Hello hi and a bunch of non-xml characters &nbsp; etc...</p>
<ul class='abc'>
  <li><img src='1.jpg' /></li>
  <li><img src='2.jpg' /></li>
</ul>

我想查询这个“xml”并获得以下结果:

<img src='1.jpg' />
<img src='2.jpg' />

因此我写了以下查询:

SELECT
    p.value('(.)[1]', 'nvarchar(100)')
FROM
(
    SELECT
        CAST(SUBSTRING(Description, CHARINDEX('<ul class=''abc''>', Description), LEN(Description)) AS XML) AS Xml
    FROM Table
        WHERE Description LIKE '%<ul class=''abc''>%'
) AS Result CROSS APPLY Xml.nodes('/ul/li') t(p)

但我的所有结果都是NULL。看来我在XML选择器中做错了什么......我做错了什么?

1 个答案:

答案 0 :(得分:1)

您需要使用query代替value

DECLARE @html NVARCHAR(MAX) = N'
<p>Hello hi and a bunch of non-xml characters &nbsp; etc...</p>
<ul class=''abc''>
  <li><img src=''1.jpg'' /></li>
  <li><img src=''2.jpg'' /></li>
</ul>'

SELECT
    p.query('.')
FROM
(
    SELECT CAST(SUBSTRING(@html, CHARINDEX('<ul class=''abc''>', @html), LEN(@html)) AS XML) AS XML
) AS Result 
CROSS APPLY xml.nodes('/ul/li/img') t(p)