【问题标题】:SQL Server for xml path with double elements用于带有双元素的 xml 路径的 SQL Server
【发布时间】:2018-01-29 15:38:06
【问题描述】:

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

【问题讨论】:

  • 在一个有效的 xml 文档中不能有多个根。如果您多次声明&lt;types&gt;,那么它不是您的根。

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


【解决方案1】:

这会返回你想要的:

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 是由几个片段组成的。而这样的结果可能是这些片段之一没有任何问题......

【讨论】:

  • 正是,这正是我所需要的。
【解决方案2】:

我想输出为:

<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>
^

你不能有多个根元素。

【讨论】:

  • 嗯,一般来说它是无效的 XML,但是 SQL-Server 可以处理这个......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多