XQuery returning an error..?

只谈情不闲聊 提交于 2019-12-02 06:27:44

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/10314562/xquery-returning-an-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!