Sql server 尝试使用XML节点从XML提取IP

Sql server 尝试使用XML节点从XML提取IP,sql-server,xml,tsql,Sql Server,Xml,Tsql,从下面的xml中,我试图提取IP,但这不起作用。我不确定我在哪里犯了错误 declare @xml xml set @xml='<auditElement> <RequestOrigination> <IP>20.20.20.20</IP> </RequestOrigination> </auditElement>' 需要的输出: IP 20.20.20.20 你就快到了!2个小错误 decla

从下面的xml中,我试图提取IP,但这不起作用。我不确定我在哪里犯了错误

declare @xml xml

set @xml='<auditElement>
  <RequestOrigination>
    <IP>20.20.20.20</IP>
     </RequestOrigination>
</auditElement>'
需要的输出:

IP
20.20.20.20

你就快到了!2个小错误

 declare @xml xml

set @xml='<auditElement>
  <RequestOrigination>
    <IP>20.20.20.20</IP>
     </RequestOrigination>
</auditElement>'

SELECT @xml

select 
 b.value('IP[1]','nvarchar(100)')
 from  @xml.nodes('//auditElement/RequestOrigination') as org(b)
declare@xml
set@xml=
20.20.20.20
'
选择@xml
挑选
b、 值('IP[1],'nvarchar(100)'))
从@xml.nodes('//auditElement/RequestOrigination')作为组织(b)
不需要
.nodes()

而且在
IP
之前不需要
@
。这将尝试读取名为“IP”的属性,但您正在读取*元素的内容(text()-node)。您的代码适用于以下情况:

<SomeElement IP="20.20.20.20">

你是对的,
@
是错的,这是第一个小错误。但是
Xpath
开头的双斜杠不是一个好主意。这引发了一场深度搜索。它将在XML中的任何位置查找元素
。在这个非常简单的例子中,它不会有什么区别,但是对于一个更大的结构,它可能会返回错误的结果,并且会变得非常缓慢。。。
<SomeElement IP="20.20.20.20">
declare @xml xml

set @xml='<auditElement>
  <RequestOrigination>
    <IP>20.20.20.20</IP>
     </RequestOrigination>
</auditElement>';

SELECT @xml.value('(/auditElement/RequestOrigination/IP/text())[1]','varchar(20)');