user3518362
user3518362

Reputation: 15

Xquery : querying xml with key value pair in t-sql

In the below code block I'm able to query till DataElements. for below xml

DECLARE @xmlString XML;
SELECT @xmlString='<Activity xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <ActivityCode>570</ActivityCode>
  <ActivityId>0011d966-fa28-440c-9196-5dbe3c40b2ac</ActivityId>
  <CreateDateTime>2014-06-19T06:57:46.9854126-04:00</CreateDateTime>
  <DataElements xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <a:KeyValueOfstringDataElementLjh4bohd>
      <a:Key>AgentId</a:Key>
      <a:Value>
        <DataType>String</DataType>
        <Name>AgentId</Name>
        <Value>abc\xyxaa</Value>
      </a:Value>
    </a:KeyValueOfstringDataElementLjh4bohd>
    <a:KeyValueOfstringDataElementLjh4bohd>
      <a:Key>PhoneCallStartTime</a:Key>
      <a:Value>
        <DataType>String</DataType>
        <Name>PhoneCallStartTime</Name>
        <Value>06/19/2014 10:57:47</Value>
      </a:Value>
    </a:KeyValueOfstringDataElementLjh4bohd>
  </DataElements>
</Activity

> below XQery

SELECT @xmlString.query('for $activity in /Activity
let $activityId := $activity/DataElements

return data($activityId)
') AS [activityId]
GO

is giving me the result:

AgentIdStringAgentIdabc\xyxaaPhoneCallStartTimeStringPhoneCallStartTime06/19/2014 10:57:47

But what I want is if I pass AgentId , I should get abc\xyxaa and if I pass PhoneCallStartTime, I should get 06/19/2014 10:57:47. Please help

Upvotes: 0

Views: 1142

Answers (1)

Jens Erat
Jens Erat

Reputation: 38702

Use predicates and axis steps to select and filter the results. Similar to the code you used:

for $activity in /Activity
return data($activity/DataElements//a:Value[Name="PhoneCallStartTime"]/Value)

There is a namespace involved here. You either have to

  • declare the namespace a="http://schemas.microsoft.com/2003/10/Serialization/Arrays or
  • ignore the namespace of the element and use the wildcard namespace operator *: instead of a: for the Value element.

Upvotes: 1

Related Questions