Sql server SQL Server FOR XML路径:设置XML声明或处理指令;“xml样式表”;最上面

Sql server SQL Server FOR XML路径:设置XML声明或处理指令;“xml样式表”;最上面,sql-server,xml,for-xml-path,processing-instruction,xml-declaration,Sql Server,Xml,For Xml Path,Processing Instruction,Xml Declaration,我想设置一条处理指令,将样式表包含在XML之上: xml声明也存在同样的问题(例如) 所需结果: <?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?> <TestPath> <Test>Test</Test> <SomeMore>SomeMore</SomeMore> </TestPath> 产生以下结果: <TestPath>

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

xml声明也存在同样的问题(例如

所需结果:

<?xml-stylesheet type="text/xsl" href="stylesheet.xsl"?>
<TestPath>
  <Test>Test</Test>
  <SomeMore>SomeMore</SomeMore>
</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);
选择CAST(
'
试验
再
'作为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]
')

事实证明,har07的伟大答案不适用于XML声明。我能找到的唯一方法是:

DECLARE @ExistingXML XML=
(
    SELECT 
        'Test' AS Test,
        'SomeMore' AS SomeMore
    FOR XML PATH('TestPath'),TYPE
);

DECLARE @XmlWithDeclaration NVARCHAR(MAX)=
(
    SELECT N'<?xml version="1.0" encoding="UTF-8"?>'
           +
           CAST(@ExistingXml AS NVARCHAR(MAX))
);
SELECT @XmlWithDeclaration;
DECLARE@ExistingXML=
(
挑选
“测试”作为测试,
“SomeMore”作为SomeMore
对于XML路径('TestPath'),键入
);
DECLARE@XmlWithDeclaration NVARCHAR(最大值)=
(
选择N“”
+
强制转换(@ExistingXml作为NVARCHAR(MAX))
);
选择@XmlWithDeclaration;

此步骤完成后,您必须停留在
字符串
行中,任何到真实XML的转换都将给出错误(当编码不是
UTF-16
时),或者将忽略此XML声明。

非常好的输入,谢谢!在他们找到类似于
top-processing-instruction()
的东西之前,这是一个非常好的解决方法!您好,har07,我只需要处理添加xml声明的问题,我想,这可以类似地完成,但事实并非如此。我用(非常明显的)解决方案添加了一个答案。。。
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('')
DECLARE @ExistingXML XML=
(
    SELECT 
        'Test' AS Test,
        'SomeMore' AS SomeMore
    FOR XML PATH('TestPath'),TYPE
);

DECLARE @XmlWithDeclaration NVARCHAR(MAX)=
(
    SELECT N'<?xml version="1.0" encoding="UTF-8"?>'
           +
           CAST(@ExistingXml AS NVARCHAR(MAX))
);
SELECT @XmlWithDeclaration;