如何将 XML 子节点作为字符串以及父属性获取? [英] How to get XML subnodes as strings along with parent attributes?

查看:26
本文介绍了如何将 XML 子节点作为字符串以及父属性获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to parse xml which consist of nodes having attributes and subnodes. The result should be attribute of parent with xml of child node

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"/>

推荐答案

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" />

这篇关于如何将 XML 子节点作为字符串以及父属性获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆