SQL 具有双元素的 xml 路径的服务器

SQL Server for xml path with double elements

我正在尝试使用 FOR XML PATH 在 SQL Server 2012 中创建一个 xml 输出。
可以做些什么来获得所需的输出?

我想输出为:

<types>
    <type>
        <type>FirstType</type>
        <attribute>FirstAttribute</attribute>
    </type>
</types>
<types>
    <type>
        <type>SecondType</type>
        <attribute>SecondAttribute</attribute>
    </type>
</types>
<types>
    <type>
        <type>ThirdType</type>
        <attribute>ThirdAttribute</attribute>
    </type>
</types>

我的代码:

DECLARE @table TABLE (
type VARCHAR(50)
, attribute VARCHAR(50)
)

SELECT T1.type
, T1.attribute
FROM @table AS T1
FOR XML path('type'), root('types')

给我错误的输出:

<types>
    <type>
        <type>FirstType</type>
        <attribute>FirstAttribute</attribute>
    </type>
    <type>
        <type>SecondType</type>
        <attribute>SecondAttribute</attribute>
    </type>
    <type>
        <type>ThirdType</type>
        <attribute>ThirdAttribute</attribute>
    </type>
</types>

I would like to output to be:

<types>
<type>
    <type>FirstType</type>
    <attribute>FirstAttribute</attribute>
</type> </types> <types>
<type>
    <type>SecondType</type>
    <attribute>SecondAttribute</attribute>
</type> </types> <types>
<type>
    <type>ThirdType</type>
    <attribute>ThirdAttribute</attribute>
</type> 
</types>

您想要的输出格式甚至不正确XML:

XML Parsing Error: junk after document element
Location: https://www.w3schools.com/xml/xml_validator.asp
Line Number 7, Column 1:
<types>
^

不能有多个根元素。

这returns你想要的:

DECLARE @table TABLE (
[type] VARCHAR(50)
, attribute VARCHAR(50)
)
INSERT INTO @table VALUES('FirstType','FirstAttribute')
                        ,('SecondType','SecondAttribute')

SELECT T1.type AS [type/type]
, T1.attribute AS [type/attribute]
FROM @table AS T1
FOR XML path('types');

但请注意:由于缺少根节点,因此无效。 SQL-服务器的XML引擎可以解决这个问题,但其他引擎可能会失败...

我认为,SQL 服务器并没有那么严格,因为 - 通常 - XML 是由多个片段构建的。而这样的结果可能是这些片段之一没有任何问题...