简体   繁体   中英

Read value in XML Node - T-SQL

This is my code.......

DECLARE @XML AS XML;

SET @XML = CAST('<Session id="ID969138672" realTimeID="4300815712">

  <VarValues>
    <varValue id="ID123" source="Internal" name="DisconnectedBy">VisitorClosedWindow</varValue>
    <varValue id="ID1234" source="PreChat"  name="email">1234@mail.ru</varValue>
  </VarValues>

</Session>
' AS XML)

SELECT 
 xmlData.Col.value('@id','varchar(max)')
,xmlData.Col.value('@source','varchar(max)')
,xmlData.Col.value('@name','varchar(max)')
FROM @XML.nodes('//Session/VarValues/varValue') xmlData(Col);

This is the output.....

在此输入图像描述

How can I include the actual values of the varValue?

I need to read the values VisistorClosedWindow and 1234@mail.ru values as well

You can get that by doing this:

xmlData.Col.value('.','varchar(max)')

So the select would be:

SELECT 
 xmlData.Col.value('@id','varchar(max)')
,xmlData.Col.value('@source','varchar(max)')
,xmlData.Col.value('@name','varchar(max)')
,xmlData.Col.value('.','varchar(max)')
FROM @XML.nodes('//Session/VarValues/varValue') xmlData(Col);

Just use the .value('.', 'varchar(50) ) line for that:

SELECT 
     xmlData.Col.value('@id','varchar(25)'),
     xmlData.Col.value('@source','varchar(50)'),
     xmlData.Col.value('@name','varchar(50)'),
     xmlData.Col.value('.','varchar(50)')         -- <== this gets your the element's value
FROM @XML.nodes('//Session/VarValues/varValue') xmlData(Col);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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