使用MSSQL从XML中解析值

时间:2016-02-05 13:55:23

标签: xml

我在表的列中有以下XML结构:

<font class="nav">
  <a onMouseOver="ShowMenu( event, '107349267', 'yes', '431539056')" href="#"    onMouseout="delayhidemenu()">
    <b>107349267</b>
  </a>
</font>

我很擅长解析大多数父节点,但我没有看到我的能力:

  SELECT 
  cast(TransactionId as xml).value('(/font class//b/node())[1]',     'nvarchar(max)') as TransId
  FROM dbo.TableA

任何帮助?

1 个答案:

答案 0 :(得分:0)

想出来:

CREATE FUNCTION [dbo].[ParseHTMLFromString]
(
 @HTML_STRING VARCHAR(MAX) -- Variable for string
)
RETURNS VARCHAR(MAX)
BEGIN

DECLARE @STRING VARCHAR(MAX)
Declare @Xml AS XML
SET @Xml = CAST(('<A>'+ REPLACE(REPLACE(REPLACE(REPLACE(@HTML_STRING
    ,'<','@*'),'>','!'),'@','</A><A>'),'!','</A><A>') +'</A>') AS XML)

;WITH CTE AS (SELECT A.value('.', 'VARCHAR(MAX)') [A] 
     FROM @Xml.nodes('A') AS FN(A) WHERE CHARINDEX('*',
     A.value('.', 'VARCHAR(MAX)'))=0 
     AND ISNULL(A.value('.', 'varchar(max)'),'')<>'')

SELECT @STRING=STUFF((SELECT ' ' + [A] FROM CTE FOR XML PATH('')),1,1,'')
RETURN @STRING
END