草庐IT

sql-server - XML 路径的 SQL Server : Set xml-declaration or processing instruction "xml-stylesheet" on top

coder 2024-06-27 原文

我想设置一个处理指令以在 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>

我的研究让我了解了节点测试语法和processing-instruction() .

这个

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

关于sql-server - XML 路径的 SQL Server : Set xml-declaration or processing instruction "xml-stylesheet" on top,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33806454/

有关sql-server - XML 路径的 SQL Server : Set xml-declaration or processing instruction "xml-stylesheet" on top的更多相关文章

随机推荐