简体   繁体   English

SQL Server:如何获取指定属性的 XML 元素的值?

[英]SQL Server: How to get the value of a XML element specifying an attribute?

For the usage in a SQL query I need to get the value of a specific XML element.对于在 SQL 查询中的使用,我需要获取特定 XML 元素的值。 The XML element is specified by its attribute. XML 元素由其属性指定。

My XML elements looks like this:我的 XML 元素如下所示:

<translations>
  <value lang="en-US">example</value>
  <value lang="de-DE">Beispiel</value>
</translations>

and the value I am looking for would be "example" when I specify lang to be "en-US".当我将 lang 指定为“en-US”时,我正在寻找的值将是“example”。

I found a way to get this value by using the query() function and afterwards the value() function.我找到了一种通过使用 query() 函数然后使用 value() 函数来获取此值的方法。

declare @S varchar(max)

set @S =
'<translations>
  <value lang="en-US">example</value>
  <value lang="de-DE">Beispiel</value>
</translations>'

declare @X xml

set @X = CAST(@S as xml)

select @X.query('/translations/value[@lang="en-US"]').value('.','varchar(max)')

This select statement return the value "example" I am looking for by using the query() and value() function.这个 select 语句通过使用 query() 和 value() 函数返回我正在寻找的值“example”。 But is there also a - more convenient - way to only use value() OR query()?但是还有一种 - 更方便 - 只使用 value() 或 query() 的方法吗?

Thank you in advance!先感谢您!

Sure there is...当然有...

You also can shorten the declaration:您还可以缩短声明:

declare @X xml=
'<translations>
  <value lang="en-US">example</value>
  <value lang="de-DE">Beispiel</value>
</translations>';

select @X.value('(/translations/value[@lang="en-US"])[1]','varchar(max)');

The point is, that you need a singleton result when you are using .value() .关键是,当您使用.value()时,您需要一个单例结果。 You achieve this by putting the XPath in paranthesis and force the first element to be taken (in this case it's the only element).您可以通过将XPath放在括号中并强制采用第一个元素(在这种情况下它是唯一的元素)来实现这一点。

Btw: If you need this (and sooner or later you will need this...), you might put the "en-US" as parameter into your query like this:顺便说一句:如果你需要这个(迟早你会需要这个......),你可以将“en-US”作为参数放入你的查询中,如下所示:

declare @prm VARCHAR(10)='en_US';
select @X.value('(/translations/value[@lang=sql:variable("@prm")])[1]','varchar(max)');

You can reach the similar, but with a value of the actual query by using sql:column() .您可以通过使用sql:column()达到类似的,但具有实际查询的值。

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

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