tsql XML显式路径

时间:2018-05-07 11:30:30

标签: sql-server xml tsql cdata for-xml

我有疑问:

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。

2 个答案:

答案 0 :(得分:1)

使用此查询...

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>

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

答案 1 :(得分:1)

我不太确定,你真正想要的是什么。我假设您的根节点应为<customers>(复数),而每行为<customer>。我假设NameSurName是您桌子中的列。

可能,您正在寻找:

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-Server开发人员决定不再支持这个......

如果您存储包含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>