提问人:Alexander Brühl 提问时间:2/2/2018 最后编辑:ShnugoAlexander Brühl 更新时间:2/10/2018 访问量:1135
在 SQL 中创建 XML(FOR XML EXPLICIT)
Create XML in SQL (FOR XML EXPLICIT)
问:
在 SQL Server 中创建一些 XML 需要一点帮助。
生成的 XML 应如下所示:
<?xml version="1.0" encoding="utf-8"?>
<Root Version="2.17" KFZ="XX-DD 389">
<Head name="ExecuteAnswer">
<Key name="AnswerStatus" value="-OK" />
<Key name="MsgId"><![CDATA[KFHB0907896aAUH223]]></Key>
<Section name="Command">
<Key name="Name" value="SetNewCommand" />
<Key name="Param0"><![CDATA[XX-DD 389]]></Key>
<Key name="Param1"><![CDATA[]]></Key>
<Key name="Param2"><![CDATA[0987asfdsafhdsSS]]></Key>
<Key name="Param3"><![CDATA[0097aSSSHSDOPir0]]></Key>
</Section>
</Head>
<Data></Data>
</Root>
我被困在添加到XML中,如果我添加它,我会得到这个错误:<Section>
[Section!3!name]
error -> 键将被部分覆盖
法典:
SELECT
1 AS Tag,
NULL AS Parent,
'2.17' AS [Root!1!Version],
'XX-DD 389' AS [Root!1!KFZ],
NULL AS [Head!2!name!Element],
NULL AS [Key!3!name],
NULL AS [Key!3!value],
NULL AS [Key!3!CDATA]
UNION ALL
SELECT
2 as Tag,
1 as Parent,
NULL,
NULL,
'ExecuteAnswer',
NULL,
NULL,
NULL
UNION ALL
SELECT
3 as Tag,
2 as Parent,
NULL,
NULL,
NULL,
'AnswerStatus',
'-OK',
NULL
UNION ALL
SELECT
3 as Tag,
2 as Parent,
NULL,
NULL,
NULL,
'MsgId',
NULL,
'KFHB0907896aAUH223'
FOR XML EXPLICIT
谁能帮帮我?
问候亚历克斯
答:
1赞
Shnugo
2/2/2018
#1
正如评论中指出的那样,没有理由再......它在语义上与正确转义的正常节点完全相同。CDATA
text()
但是,有时遗留系统或第三方工具需要它。
您必须知道的一点:除了强制转换和手动追加它之外,没有机会将 添加到 XML 中。xml declaration
NVARCHAR(MAX)
因此,如果您无论如何都必须检查字符串,则可以使用,创建as并简单地将这些占位符更改为开始和结束字符,从而轻松创建XML和简单。FOR XML PATH()
CDATA
<xdata>content</xdata>
REPLACE
CDATA
但是:这是一种EXPLICIT
SELECT
1 AS Tag,
NULL AS Parent,
'2.17' AS [Root!1!Version],
'XX-DD 389' AS [Root!1!KFZ],
NULL AS [Head!2!name!Element],
NULL AS [Key!3!name],
NULL AS [Key!3!value],
NULL AS [Key!3!!CDATA],
NULL AS [Section!4!name],
NULL AS [Key!5!name],
NULL AS [Key!5!value],
NULL AS [Key!6!name],
NULL AS [Key!6!!CDATA]
UNION ALL
SELECT
2 as Tag,
1 as Parent,
NULL,
NULL,
'ExecuteAnswer',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
UNION ALL
SELECT
3 as Tag,
2 as Parent,
NULL,
NULL,
NULL,
'AnswerStatus',
'-OK',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL
UNION ALL
SELECT
3 as Tag,
2 as Parent,
NULL,
NULL,
NULL,
'MsgId',
NULL,
'KFHB0907896aAUH223',
NULL,
NULL,
NULL,
NULL,
NULL
UNION ALL
SELECT
4 as Tag,
2 as Parent,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
'Command',
NULL,
NULL,
NULL,
NULL
UNION ALL
SELECT
5 as Tag,
4 as Parent,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
'Name',
'SetNewCommand',
NULL,
NULL
UNION ALL
SELECT
6 as Tag,
4 as Parent,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
'Param0',
'XX-DD 389'
FOR XML EXPLICIT
评论
OPTION EXPLICIT
CDATA
CDATA
CDATA