如何在sql这个例子中获取节点a和img?

时间:2016-09-19 13:49:42

标签: html sql xml

我的代码:

 Declare @htmlXML xml =' 
 <li>
           <a class="group" onclick="changeimage(http://laptopbatteryone.com/media/catalog/product/cache/1/thumbnail/1200x1200/9df78eab33525d08d6e5fb8d27136e95/l/b/lb-ac48-44-back.jpg)" href="javascript:;" title="" >
                <img src="http://laptopbatteryone.com/media/catalog/product/cache/1/thumbnail/250x250/9df78eab33525d08d6e5fb8d27136e95/l/b/lb-ac48-44-back.jpg" alt="Acer Aspire 1420P Battery [6 Cells 4400mAh 10.8V]"/>
            </a>
        </li>
        '



 SELECT  n.c.value('@alt','nvarchar(max)') as Brand
        ,t.v.value('@onclick','nvarchar(max)') as [URL]
        FROM @htmlXML.nodes('li/a') as t(v)
        outer apply t.v.nodes('li/a/img') as n(c)

我想在sql中输出这个。 输出:

url img in <a onclick : http://laptopbatteryone.com/media/catalog/product/cache/1/thumbnail/1200x1200/9df78eab33525d08d6e5fb8d27136e95/l/b/lb-ac48-44-back.jpg

alt img in img tag: Acer Aspire 1420P Battery [6 Cells 4400mAh 10.8V]

感谢您的朋友提示

1 个答案:

答案 0 :(得分:0)

除此之外,HTML不是XML(我真的开始微笑着再次阅读你的问题,看看herehere),在这种情况下它可能会起作用(仍然会不建议这个.. ..

Declare @htmlXML xml =
'<li>
  <a class="group" onclick="changeimage(http://laptopbatteryone.com/media/catalog/product/cache/1/thumbnail/1200x1200/9df78eab33525d08d6e5fb8d27136e95/l/b/lb-ac48-44-back.jpg)" href="javascript:;" title="">
    <img src="http://laptopbatteryone.com/media/catalog/product/cache/1/thumbnail/250x250/9df78eab33525d08d6e5fb8d27136e95/l/b/lb-ac48-44-back.jpg" alt="Acer Aspire 1420P Battery [6 Cells 4400mAh 10.8V]" />
  </a>
</li>';

- 查询

 SELECT  a.value('@class','nvarchar(max)') AS a_class
        ,a.value('@onclick','nvarchar(max)') AS a_onclick
        ,SUBSTRING(a.value('@onclick','nvarchar(max)'),13,LEN(a.value('@onclick','nvarchar(max)'))-13) AS a_onclick_URL
        ,a.value('@href','nvarchar(max)') AS a_href
        ,img.value('@src','nvarchar(max)') as img_src
        ,img.value('@alt','nvarchar(max)') as img_alt
        FROM @htmlXML.nodes('li/a') as A(a)
        outer apply a.nodes('img') as B(img);

结果(实际上是行...)

a_class:   group    
a_onclick: changeimage(http://laptopbatteryone.com/media/catalog/product/cache/1/thumbnail/1200x1200/9df78eab33525d08d6e5fb8d27136e95/l/b/lb-ac48-44-back.jpg)  
URL:       http://laptopbatteryone.com/media/catalog/product/cache/1/thumbnail/1200x1200/9df78eab33525d08d6e5fb8d27136e95/l/b/lb-ac48-44-back.jpg   
a_href:    javascript:; 
img_src:   http://laptopbatteryone.com/media/catalog/product/cache/1/thumbnail/250x250/9df78eab33525d08d6e5fb8d27136e95/l/b/lb-ac48-44-back.jpg 
img_alt:   Acer Aspire 1420P Battery [6 Cells 4400mAh 10.8V]