سؤال

Below is the XML file -

<Continents>
  <Continent n="Asia">
    <Country n="Thailand">
      <City>
        <Name>Bangkok</Name>
        <Desc>Capital on Thailand</Desc>
      </City>
    </Country>
    <Country n="India">
      <City>
        <Name>New Delhi</Name>
        <Desc>Capital on India</Desc>
      </City>
      <City>
        <Name>Mumbai</Name>
        <Desc>Financial capital on India</Desc>
      </City>
      <City>
        <Name>Chennai</Name>
        <Desc>A very good city</Desc>
      </City>
    </Country>
  </Continent>
</Continents>

Using baseX, I am writing a query to display the Name of cities containing the word Capital but is returning error. The query is -

/Continents/Continent[contains(Country/City/Desc,'Capital')]/Country/City/Name

and the error is - Error: [XPTY0004] Single item expected, (element Desc { ... }, element Desc { ... }, ...) found.

Please help me out.. Is it required to use FLWOR for such queries?

هل كانت مفيدة؟

المحلول

Your original query could have been rewritten as follows...

/Continents/Continent[
  some $x in Country/City/Desc satisfies contains($x,'Capital')]
  /Country/City/Name

...or...

/Continents/Continent[
  for $x in Country/City/Desc
  where contains($x,'Capital')
  return $x]/Country/City/Name

...but both of the queries will return all countries of any continent that contains a city description containing 'Capital'. Instead, this is probably what you are looking for:

/Continents/Continent/Country/City[contains(Desc,'Capital')]/Name

You may as well use the contains text expression to ignore case, diacritics, etc. in your key words:

/Continents/Continent/Country/City[Desc contains text 'Capital']/Name

Hope this helps.

نصائح أخرى

Your predicate [contains(Country/City/Desc,'Capital')] selects all Desc nodes containing 'Capital' for the Continent element, so it evaluates to three elements. To fix this, just move the predicate to the City element (after all, you want to filter the City elements, not the Continent). I didn't test it, but i would expect this to work:

/Continents/Continent/Country/City[contains(Desc,'Capital')]/Name
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top