sql-server - SQL Server 用于具有双元素的 xml 路径

标签 sql-server xml tsql xpath for-xml-path

我正在尝试使用 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>

最佳答案

这将返回您想要的内容:

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-Server 的 XML 引擎可以处理这个问题,但其他引擎可能会失败......

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

关于sql-server - SQL Server 用于具有双元素的 xml 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48504855/

相关文章:

java - 如何使用 JDOM 删除 SOAP 信封并将 XML 的其余部分作为字符串返回?

sql-server - EXEC 的费用是多少?

SQL:在单个字段中包含多个值的嵌套 SELECT

sql-server - 将存储过程返回值分配给 VBA 变量

sql-server - SSIS、dtsx 和部署包

java - 在 API 19 设备上膨胀 TextInputEditText 时出错

sql-server - 使用 Windows 任务计划程序执行存储过程

java - 使用 XPath 将 XML 信息提取到 List<Map>

sql - OBJECT_ID 在 SQL Server 中有什么作用?

sql - 为什么 SQLServerCE 查询执行表扫描,这是一个问题?