如何获取XML子节点作为字符串以及父属性?

时间:2019-02-20 16:12:41

标签: sql sql-server xml sql-server-2016

我需要解析由具有属性的节点和子节点组成的xml。结果应该是父节点的属性,子节点的xml

SUMX(my_table, VALUE(my_table[contador]))

输出为

declare @xml xml
set @xml = '<root>
<group Description="firstgroup">
    <nodeA age="10" birthplace="Anchorage"/>
    <nodeB mode="A" ability="read"/>
</group>
<group Description="nextgroup">
    <nodeA age="10" birthplace="London"/>
    <nodeB count="2" birthplace="Paris"/>
</group>
</root>'
select
        c.value('@Description', 'varchar(max)') as 'Description'
from @xml.nodes('/root/*') as T(c)

但是我需要

Description
===========
firstgroup   
nextgroup

2 个答案:

答案 0 :(得分:1)

也许是这样的:

示例

Select c.value('@Description', 'varchar(max)') as 'Description'
      ,AsString = convert(varchar(max),c.query('./*[2]') )
      ,AsXML    = c.query('./*[2]')
 From  @xml.nodes('/root/*') as T(c)

返回

enter image description here

答案 1 :(得分:1)

select
        c.value('@Description', 'varchar(max)') as 'Description'
        , c.query('./nodeB')  as Content
from @xml.nodes('/root/*') as T(c)

-- Results to:
Description Content
firstgroup  <nodeB mode="A" ability="read" />
nextgroup   <nodeB count="2" birthplace="Paris" />