简体   繁体   English

检索SQL Server中具有相同前缀的所有XML元素

[英]Retrieve all XML elements with the same prefix in SQL Server

I have an XML file in a format similar to: 我有一个类似于以下格式的XML文件:

<XML>
   <Field1>100</Field1>
   <Field2>200</Field2>
   <Field3>300</Field3>
   <Test>400</Test>
</XML>

I need to write a query that will get all of the element values that start with Field . 我需要编写一个查询来获取以Field开头的所有元素值。 So given the XML above the result should be 因此,鉴于上面的XML,结果应该是

FieldVal
--------
100     
200     
300

I've tried the following but it does not work: 我尝试了以下但它不起作用:

Select 
    xc.value('text()', 'int')
From 
    @XMLData.nodes('/XML/[starts-with(name(), ''Field'')]') As xt(xc)

NOTE: I am well aware that this task could be easily done if I reformatted my XML but unfortunately I have no control over the format of the XML. 注意:我很清楚如果我重新格式化我的XML可以轻松完成这项任务,但遗憾的是我无法控制XML的格式。

One way is 一种方法是

declare @XMLData xml ='<XML>
   <Field1>100</Field1>
   <Field2>200</Field2>
   <Field3>300</Field3>
   <Test>400</Test>
</XML>'

Select 
    xc.value('.', 'int')
From @XMLData.nodes('/XML/*') As xt(xc)
WHERE xc.value('local-name(.)', 'varchar(50)') LIKE 'Field%'

Prefix name with special character and check contains instead. 具有特殊字符的前缀名称和检查包含。

declare @x xml ='<XML>
   <Field1>100</Field1>
   <Field2>200</Field2>
   <Field3>300</Field3>
   <Test>400</Test>
</XML>';

select t.n.value('.','varchar(100)')
from @x.nodes ('XML/*[contains(concat("$",local-name()),"$Field")]') t(n);

I think it's this what you are looking for: 我认为这就是你要找的东西:

DECLARE @xml XML=
'<XML>
   <Field1>100</Field1>
   <Field2>200</Field2>
   <Field3>300</Field3>
   <Test>400</Test>
</XML>';

SELECT Fld.value('.','int') AS FieldOnly
FROM @xml.nodes('/XML/*[substring(local-name(.),1,5)="Field"]') AS A(Fld)

Just because of the discussion in comments: 仅仅因为评论中的讨论:

DECLARE @fldName VARCHAR(100)='Field';
SELECT Fld.value('.','int') AS FieldOnly
FROM @xml.nodes('/XML/*[substring(local-name(.),1,string-length(sql:variable("@fldName")))=sql:variable("@fldName")]') AS A(Fld)

Change the first line to "Test" ( case sensitive! ), and you'd get just the one row with 400... 将第一行更改为“Test”( 区分大小写! ),然后您将获得400行的一行...

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

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