How to get this output with XQuery? [duplicate]
سؤال
Possible Duplicate:
XQuery returning an error..?
Below is the XML file -
<Continents>
<Continent name="Asia">
<Country name="Japan">
<City name="Tokyo"><Desc>Tokoyo is a most populated City</Desc></City>
<City name="Horishima"><Desc>What to say.. Faced the destruction due to Atom Bomb</Desc></City>
</Country>
<Country name="India">
<City name="New Delhi"><Desc>Capital of India</Desc></City>
<City name="Mumbai"><Desc>Financial Capital of India</Desc></City>
<City name="Lucknow"><Desc>City of Nawabs</Desc></City>
</Country>
</Continent>
</Continents>
I want to list Cities for Country="India"
My XQuery FLWOR code is -
for $x in doc("Continent")/Continents/Continent
where $x/Country/@name='India'
return $x/Country/City/@name
I am wishing output as -
name="New Delhi" name="Mumbai" name="Lucknow"
but getting output as -
name="Tokyo" name="Horishima" name="New Delhi" name="Mumbai" name="Lucknow"
Can anybody help me to get correct output? Also how to get it on separate line?
المحلول
You asked almost the exact same question here and the same answer applies here, too. What you want is:
doc("Continent")/Continents/Continent/Country[@name = 'India']/City/@name
If you want each result on its own line, try this:
string-join(
doc("Continent")/Continents/Continent/Country[@name = 'India']/City/@name,
' '
)
This should result in:
New Delhi
Mumbai
Lucknow
نصائح أخرى
You could also rewrite your FLWOR a bit to get the wanted results:
for $x in doc("Continent")/Continents/Continent/Country
where $x/@name='India'
return $x/City/@name
(Note that I move the /Country part)
If necessary you can wrap this FLWOR in a string-join as suggested by Leo the same way he wraps his XPath expression alternative..
/*/*/Country[@name='India']/City/concat('name="', @name, '" ')
Note: This also happens to be a pure XPath 2.0 expression.