如何从 SQL Server 中的 XML 元素获取特定属性 [英] How to get a particular attribute from XML element in SQL Server

查看:45
本文介绍了如何从 SQL Server 中的 XML 元素获取特定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表的一列中有类似以下 XML 的内容:

I have something like the following XML in a column of a table:

<?xml version="1.0" encoding="utf-8"?>
<container>
  <param name="paramA" value="valueA" />
  <param name="paramB" value="valueB" />
  ...
</container>

我正在尝试通过 TSQL 从 XML 中获取 valueB 部分

I am trying to get the valueB part out of the XML via TSQL

到目前为止我得到了正确的节点,但现在我不知道如何获取属性.

So far I am getting the right node, but now I can not figure out how to get the attribute.

select xmlCol.query('/container/param[@name="paramB"]') from LogTable

我想我可以将/@value 添加到最后,但是 SQL 告诉我属性必须是节点的一部分.我可以找到很多选择子节点属性的示例,但没有关于兄弟属性的示例(如果这是正确的术语).

I figure I could just add /@value to the end, but then SQL tells me attributes have to be part of a node. I can find a lot of examples for selecting the child nodes attributes, but nothing on the sibling atributes (if that is the right term).

任何帮助将不胜感激.

推荐答案

尝试使用 .value 函数代替 .query :

Try using the .value function instead of .query:

SELECT 
  xmlCol.value('(/container/param[@name="paramB"]/@value)[1]', 'varchar(50)') 
FROM  
  LogTable

XPath 表达式可能返回一个节点列表,因此您需要向该潜在列表添加一个 [1] 以告诉 SQL Server 使用这些条目中的第一个(是的 - 即列表是基于 1 的 - 不是基于 0 的).作为第二个参数,您需要指定该值应该转换为什么类型——这里只是猜测.

The XPath expression could potentially return a list of nodes, therefore you need to add a [1] to that potential list to tell SQL Server to use the first of those entries (and yes - that list is 1-based - not 0-based). As second parameter, you need to specify what type the value should be converted to - just guessing here.

马克

这篇关于如何从 SQL Server 中的 XML 元素获取特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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