How to filter an XML field on multiple conditions
-
21-12-2019 - |
Question
I have a table as such:
CREATE TABLE MyTable(
Id [int] IDENTITY(1,1) NOT NULL,
XmlField xml NULL,
/// Some other fields
)
The XML field contains an XML representation of a C# Dictionary<int, string>
. E.g :
<dictionary>
<item>
<key><int>1</int></key>
<value><string>Web</string></value>
</item>
<item>
<key><int>2</int></key>
<value><string>Email</string></value>
</item>
// more item
</dictionary>
What I want to do is select all rows where XmlField contains (key = 1 with value = 'Web') and also contains (key = 2 with value = 'Email').
So far I have only managed to filter rows for 1 unique key/value match:
SELECT TableId, XmlField FROM MyTable
CROSS APPLY XmlField.nodes('/dictionary/item') x(fields)
WHERE (x.fields.value('(key/int/text())[1]', 'int') = 1
AND x.fields.value('(value/string/text())[1]', 'varchar(MAX)') = 'Web')
If I add AND (x.fields.value('(key/int/text())[1]', 'int') = 2 AND x.fields.value('(value/string/text())[1]', 'varchar(MAX)') = 'Email')
then nothing is returned (quite logically).
I have also tried not to use CROSS APPLY
and do a simple filter as such:
SELECT TableId, XmlField FROM MyTable
WHERE XmlField.exist('/dictionary/item/key/int[text() = 1]') = 1
AND XmlField.exist('/dictionary/item/value/string[text() = "Web"]') = 1
But then it acts like a OR
and would return rows where the xml contains 2 key-value pairs such as (1, Email) and (2, Web)
Solution
Something like this should do it.
select *
from MyTable as T
where T.XmlField.exist('/dictionary[item[key/int/text() = 1 and value/string/text() = "Web"] and
item[key/int/text() = 2 and value/string/text() = "Email"]]') = 1