SQL XPath查询按属性查找节点值

时间:2015-08-11 08:34:29

标签: sql-server xml xpath

我指的是How to get a particular attribute from XML element in SQL Server

我没有特定属性的节点值,而是我正在寻找节点的值,具体取决于我要查找的属性。

我从SQL中的表中的XML列中进行选择,但为了简单起见,我可以提供以下示例:

DECLARE @xml xml = CONVERT(XML, '<?xml version="1.0" encoding="UTF-8"?>
<alert>
   <hits>
      <elem name="hit">
         <elem name="scoreFactors">
            <elem name="scoreFactors">
               <elem name="factorId">FactorID 1</elem>
               <elem name="factorDesc">FactorDesc 1</elem>
               <elem name="factorValue">FactorValue 1</elem>
               <elem name="factorScore">FactorScore 1</elem>
               <elem name="factorImpact">FactorImpact 1</elem>
            </elem>
            <elem name="scoreFactors">
               <elem name="factorId">FactorID 2</elem>
               <elem name="factorDesc">FactorDesc 2</elem>
               <elem name="factorValue">FactorValue 2</elem>
               <elem name="factorScore">FactorScore 2</elem>
               <elem name="factorImpact">FactorImpact 2</elem>
            </elem>
         </elem>
       </elem>
   </hits>
</alert>')

SELECT @xml.value('(/alert/hits/elem/elem[@name="factorDesc"])[1]', 'nvarchar(max)')

我收到的所有内容都是NULL值,但我希望分别以FactorDesc 1FactorDesc 2为2行。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您正在寻找的属性位于<elem>第四级别 - 因此您需要使用此XPath:

SELECT @xml.value('(/alert/hits/elem/elem/elem/elem[@name="factorDesc"])[1]', 'nvarchar(max)')

或者使用此XPath(但提防:如果您的XML有很多<elem>个节点,这可能是杀手的性能!你&# 39;已被警告过!)

SELECT @xml.value('(/alert/hits//elem[@name="factorDesc"])[1]', 'nvarchar(max)')

更新:如果您希望所有具有factorDesc名称的节点,您可以使用以下内容:

;WITH Shredded AS
(
    SELECT 
        ElemName = xc.value('@name', 'varchar(50)'),
        ElemValue = xc.value('.', 'varchar(50)') 
    FROM
        @xml.nodes('/alert/hits//elem') AS XT(XC)
)
SELECT *
FROM Shredded
WHERE Shredded.ElemName = 'factorDesc'

答案 1 :(得分:1)

搜索所有元素:

SELECT
    t.value('.','nvarchar(max)')
FROM @xml.nodes('(alert/hits//elem[@name="factorDesc"])') AS t(t)