在 FOR XML AUTO 模式下为 XML 标签添加前缀

2021-10-01 00:00:00 xml sql sql-server

我想知道是否可以在每个 ELEMENT TAG 之前添加 TAG PREFIXFOR XML AUTO 模式的结果.

我知道使用 RAW 模式是可能的,但我需要使其尽可能分层 xml 结果

像这样:

 

<prefix:ID>值</prefix:ID><前缀:名称>值</前缀:名称></prefix:attName>

并且RAW模式下的查询将是这样的:

SELECT ID,姓名,从表名FOR XML RAW ('prefix'), ROOT('prefix:attName'), ELEMENTS

解决方案

您可以使用别名来实现:

WITH XMLNAMESPACES ('prefix' AS 前缀)SELECT ID AS [前缀:ID],名称 AS [前缀:名称]FROM TableName AS [前缀:attName]FOR XML AUTO, ROOT('prefix:attName'), ELEMENTS

I'd like to know if it is possible to add TAG PREFIX before every ELEMENT TAG in the result of FOR XML AUTO mode.

I know it's possible with RAW mode but I need to make its as hierarchy as possible xml result

Something like this:

       <prefix:attName>
        <prefix:ID>value</prefix:ID>
        <prefix:name>value</prefix:name>
      </prefix:attName>

and the query in the RAW mode will be like this:

SELECT ID, 
      Name,
FROM TableName 
FOR XML RAW ('prefix'), ROOT('prefix:attName'), ELEMENTS

解决方案

You can achieve this using Aliases:

WITH XMLNAMESPACES ('prefix' AS prefix)
SELECT  ID AS [prefix:ID], 
        Name AS [prefix:Name]
FROM    TableName AS [prefix:attName]
FOR XML AUTO, ROOT('prefix:attName'), ELEMENTS

相关文章