简体   繁体   English

SQL Server脚本-选择根的xml子节点作为(n)varchar

[英]SQL Server Script - select xml child nodes of root as (n)varchar

I need to create a SQL Server script and a part of the script is selecting the names of the immediate child nodes of the root node and convert it to a (n)varchar . 我需要创建一个SQL Server脚本,脚本的一部分是选择根节点的直接子节点的名称,并将其转换为(n)varchar I don't need the attributes or content of the node. 我不需要节点的属性或内容。

This is an example of the xml: 这是xml的示例:

declare @XML xml

set @XML = 
'
<config>
  <module1 />    
  <module2 />  
</config>
'

I want the result like this: 我想要这样的结果:

  • module1 模块1
  • module2 模块2

Note that the xml is not hardcoded and can have many different child nodes. 请注意,xml 不是硬编码的 ,可以具有许多不同的子节点。

I've already taken a look at this (msdn)link but at first sight it doesn't seem possible with those XML methods. 我已经看过这个(msdn)链接,但是乍一看,使用这些XML方法似乎是不可能的。

Many thanks, Kjell 非常感谢,Kjell

If you want the XML of the child nodes you mentioned you can use the Query method, for example; 例如,如果要使用提到的子节点的XML,则可以使用Query方法。

select 
    cast(@XML.query('//GuiConfiguration/Activities') as nvarchar(max)), 
    cast(@XML.query('//GuiConfiguration/Reservations') as nvarchar(max))

EDIT: Answer to refined question 编辑:提炼的问题的答案

To get the names of the immediate child nodes of the root you can use this; 要获得根的直接子节点的名称,您可以使用它;

select
    cast(t.c.query('local-name(.)') as nvarchar(max))
from
    @xml.nodes('//*[1]/child::node()') as t(c)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM