How to use two conditions in "where" clause in XQuery

2.6k Views Asked by At

I'm trying to extract only those <book> data that has a certain type of <xref> type and matching a list of specific xrefs using a Xquery (I'm new to this).

Here is the input data:

  <book id="6636551">
    <master_information>
        <book_xref>
            <xref type="Fiction" type_id="1">72771KAM3</xref>
            <xref type="Non_Fiction" type_id="2">US72771KAM36</xref>
        </book_xref>
    </master_information>
  </book>
  <book id="119818569">
    <master_information>
        <book_xref>
            <xref type="Fiction" type_id="1">070185UL5</xref>
            <xref type="Non_Fiction" type_id="2">US070185UL50</xref>
        </book_xref>
    </master_information>
  </book>
  <book id="119818568">
  <master_information>
        <book_xref>
            <xref type="Fiction" type_id="1">070185UK7</xref>
            <xref type="Non_Fiction" type_id="2">US070185UK77</xref>
        </book_xref>
    </master_information>
  </book>
  <book id="119818567">
    <master_information>
        <book_xref>
            <xref type="Fiction" type_id="1">070185UJ0</xref>
            <xref type="Non_Fiction" type_id="2">US070185UJ05</xref>
        </book_xref>
    </master_information>
  </book>
  <book id="38085123">
    <master_information>
        <book_xref>
            <xref type="Fiction" type_id="1">389646AV2</xref>
            <xref type="Non_Fiction" type_id="2">US389646AV26</xref>
        </book_xref>
    </master_information>
  </book>

XQuery that I'm using:

for $x in //book 
where $x//xref/@type='Fiction'
and
$x//xref=('070185UL5','070185UJ0')
return $x

The above Xquery only fetches the first book information matching the "070185UL5". I would expect it to fetch both. What is wrong? I appreciate your response.

1

There are 1 best solutions below

2
On BEST ANSWER

In the query

for $x in //book 
where $x//xref/@type='Fiction'
and
$x//xref=('070185UL5','070185UJ0')
return $x

do you intend to say

(1) "there must be at least one xref whose @type is 'Fiction' and at least one xref whose value is '070185UL5' or'070185UJ0'"

or do you intend to say

(2) "there must be at least one xref whose @type is 'Fiction' and whose value is '070185UL5' or'070185UJ0'"

Currently you are saying (1). If you want to say (2) then the query should be

for $x in //book 
where $x//xref[@type='Fiction' and .=('070185UL5','070185UJ0')]
return $x

which you can simplify to the XPath expression

//book[.//xref[@type='Fiction' and .=('070185UL5','070185UJ0')]]

With the data you have supplied the two queries give the same result, but with different data they could give different results.