admin

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

sql

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

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

但是我需要

Description   nodeBXML
===========   ========
firstgroup    <nodeB mode="A" ability="read"/>
nextgroup     <nodeB count="2" birthplace="Paris"/>

阅读 181

收藏
2021-07-01

共1个答案

admin

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" />
2021-07-01