简体   繁体   English

从SQL Server中具有相同标签名称的XML提取值

[英]Extract Value from XML having same tag name in SQL Server

I have XML variable defined below and its value. 我在下面定义了XML变量及其值。

I want to fetch the text defined between tag <TextNodeChild> in single query. 我想在单个查询中获取标记<TextNodeChild>之间定义的文本。

Kindly help. 请帮助。

Declare @XMLVariable = 
'<?xml version="1.0"?>
 <root>  
     <TextNodeParent>
         <TextNodeChild>12345</TextNodeChild>
         <TextNodeChild>67890</TextNodeChild>
         <TextNodeChild>12389</TextNodeChild>
     </TextNodeParent>
 </root>'

I need output like this: 我需要这样的输出:

12345
67890
12389

You could use the XQuery (ie XML query) .nodes() method 您可以使用XQuery(即XML查询) .nodes()方法

SELECT 
    TextNodeParent = n.value('.[1]', 'NVARCHAR(max)') 
FROM
    @XMLVariable.nodes('root/TextNodeParent/*') as p(n)

EDIT : If you want to just the select the TextNodeChild node data then little change in xml path as follow 编辑:如果您只想选择TextNodeChild节点数据,则在xml路径中进行如下更改

 @XMLVariable.nodes('root/TextNodeParent/TextNodeChild') as p(n)

Result 结果

TextNodeParent
12345
67890
12389

@YogeshSharma's solution works - here - because you have nothing but <TextNodeChild> elements under your <TextNodeParent> node. @YogeshSharma的解决方案在这里起作用,因为在<TextNodeParent>节点下,除了<TextNodeChild>元素之外,您什么都没有。

However, if you had various node, and you wanted to extract only the <TextNodeChild> ones and get their values (and ignore all others), you'd have to use something like this instead: 但是,如果你有不同的节点,和你想提取<TextNodeChild>的人,并得到他们的价值观(而忽略其他所有),你不得不使用这样的事情,而不是:

SELECT 
    TextNodeParent = XC.value('.', 'INT')
FROM
    @XMLVariable.nodes('root/TextNodeParent/TextNodeChild') as XT(XC)

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

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