加入收藏 | 设为首页 | 会员中心 | 我要投稿 温州站长网 (https://www.0577zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server – SQL Server FOR XML PATH:在顶部设置xml-declara

发布时间:2021-02-22 21:44:11 所属栏目:MsSql教程 来源:网络整理
导读:我想设置一个处理指令,在XML上包含一个样式表: 同样的问题是xml声明(例如?xml version =“1.0”encoding =“utf-8”?) 期望的结果: ?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?TestPath TestTest/Test SomeMoreSomeMore/SomeMore/TestPat

我想设置一个处理指令,在XML上包含一个样式表:

同样的问题是xml声明(例如<?xml version =“1.0”encoding =“utf-8”?>)

期望的结果:

<?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
<TestPath>
  <Test>Test</Test>
  <SomeMore>SomeMore</SomeMore>
</TestPath>

我的研究带给我节点测试语法和处理指令().

这个

SELECT 'type="text/xsl" href="stylesheet.xsl"' AS [processing-instruction(xml-stylesheet)],'Test' AS Test,'SomeMore' AS SomeMore
FOR XML PATH('TestPath')

产生这个:

<TestPath>
  <?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
  <Test>Test</Test>
  <SomeMore>SomeMore</SomeMore>
</TestPath>

我找到的所有提示告诉我将XML转换为VARCHAR,“手动”连接并将其转换回XML.但这是 – 怎么说 – 难看?

这很明显:

SELECT CAST(
'<?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
<TestPath>
  <Test>Test</Test>
  <SomeMore>SomeMore</SomeMore>
</TestPath>' AS XML);

有机会解决这个问题吗?

解决方法

还有另一种方法,它需要两个步骤,但不需要您在过程中的任何位置将XML视为字符串:
declare @result XML =
(
    SELECT 
        'Test' AS Test,'SomeMore' AS SomeMore
    FOR XML PATH('TestPath')
)
set @result.modify('
    insert <?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
    before /*[1]
')

Sqlfiddle Demo

传递给modify()函数的XQuery表达式告诉SQL Server在XML的根元素之前插入处理指令节点.

更新:

基于以下线程找到另一种替代方案:Merge the two xml fragments into one?.我个人更喜欢这种方式:

SELECT CONVERT(XML,'<?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>'),(
    SELECT 
        'Test' AS Test,'SomeMore' AS SomeMore
    FOR XML PATH('TestPath')
)
FOR XML PATH('')

Sqlfiddle Demo

(编辑:温州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读