Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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">[email protected]</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.....

enter image description here

How can I include the actual values of the varValue?

I need to read the values VisistorClosedWindow and [email protected] values as well

like image 704
Etienne Avatar asked Jul 29 '13 13:07

Etienne


2 Answers

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);
like image 151
Avitus Avatar answered Oct 10 '22 09:10

Avitus


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);
like image 21
marc_s Avatar answered Oct 10 '22 09:10

marc_s