tsql XML 显式路径

tsql XML explicit path

我有疑问:

select 1 as Tag , 0 as Parent , '<P>' + 'Name' + ' ' + 'SurName' + '</P>' as "name!1!!CDATA" from tPA_SysParamSys for xml explicit, root('customers')

哪个输出是:

<customers> <name><![CDATA[<P>Name SurName</P>]]></name> </customers>

但我想:

<customer> <customers> <name><![CDATA[<P>Name SurName</P>]]></name> </customers> </customer>

没有 EXPLICIT 和 CDATA 但有 PATH 我可以做到,但不能用 CDATA。

有了这个查询...

with c 
as 
( 
select 1 as CustomerId, 'Name1' as Name1, 'Name2' as Name2 
union select 2, 'Name1', 'Name2' 
) 
select 1 as Tag 
    , 0 as Parent 
    , CustomerId as "customer!1!customer_id!hide" 
    , null as "name!2!!CDATA" 
from c 
union 
select 2 as Tag 
    , 1 as Parent 
    , CustomerId 
    , Name1 + ' ' + Name2 as "name!2!!CDATA" 
from tCustomers c 
order by "customer!1!customer_id!hide", Tag 
for xml explicit, root('customers') 

你明白了 XML ...

<customers>
  <customer>
    <name><![CDATA[Comp1Name1 Comp1Name2]]></name>
  </customer>
  <customer>
    <name><![CDATA[Comp2Name1 Comp2Name2]]></name>
  </customer>
</customers>

受此启发 link ... https://www.experts-exchange.com/questions/26194239/CDATA-tags-appearing-incorrectly-in-XML-output-using-FOR-XML-PATH.html

我不太确定,你真正想要的是什么。我假设,您的根节点应该是 <customers>(复数),而每一行是一个 <customer>。我假设 NameSurName 是生活在您的 table.

中的列

可能是,您要找的就是这个:

DECLARE @mockupTable TABLE([Name] VARCHAR(100),SurName VARCHAR(100));
INSERT INTO @mockupTable VALUES('Smith','Tim'),('Fonda','Jane');

select 1 as Tag , 
0 as Parent ,
'<P>' + Name + ' ' + SurName + '</P>' as "customer!1!name!CDATA" 
from @mockupTable 
for xml explicit, root('customers');

结果

<customers>
  <customer>
    <name><![CDATA[<P>Smith Tim</P>]]></name>
  </customer>
  <customer>
    <name><![CDATA[<P>Fonda Jane</P>]]></name>
  </customer>
</customers>

但请允许我提问:为什么?

绝对不需要 CDATA 部分。正确转义的普通 text() 节点在语义上是相同的。 SQL-服务器开发人员甚至决定不再支持此功能...

如果您存储包含 CDATA 部分的 XML,它们将被隐式翻译。试试看:

DECLARE @xml XML=
N'<customers>
  <customer>
    <name><![CDATA[<P>Smith Tim</P>]]></name>
  </customer>
  <customer>
    <name><![CDATA[<P>Fonda Jane</P>]]></name>
  </customer>
</customers>';
SELECT @xml;

你明白了:

<customers>
  <customer>
    <name>&lt;P&gt;Smith Tim&lt;/P&gt;</name>
  </customer>
  <customer>
    <name>&lt;P&gt;Fonda Jane&lt;/P&gt;</name>
  </customer>
</customers>