SQL Server FOR XML PATH:在顶部设置xml-declaration或处理指令“xml-stylesheet”

时间:2015-11-19 14:19:35

标签: sql-server xml for-xml-path processing-instruction xml-declaration

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

同样的问题是xml声明(例如this.dataGridView1.Columns.Clear(); this.dataGridView1.AutoGenerateColumns = false; //Create Column var column1 = new DataGridViewTextBoxColumn() { Name = "firstNameColumn", /*Name of Column*/ HeaderText = "First Name", /*Title of Column*/ DataPropertyName = "FirstName" /*Name of the property to bind to cilumn*/ }; //Add column to grid this.dataGridView1.Columns.Add(column1);

期望的结果:

<?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')

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

这很明显:

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

有机会解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

还有另外一种方法,它需要两个步骤,但不需要你在过程中的任何地方将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

答案 1 :(得分:0)

当它出现时,har07的好答案不适用于XML声明。我能找到的唯一方法是:

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

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

在此步骤之后,您必须留在string行,任何转换为​​真实XML 都会出错(当编码为UTF-16之外的其他编码时)或将省略这个xml声明。