w3pop.com :: ÍøÂçѧԺ :: Xquery :: XQuery ʵÀý
Let's try to learn some basic XQuery syntax by looking at an example.
ÈÃÎÒÃÇͨ¹ýÏÂÃæÕâ¸ö°¸ÀýÀ´Ñ§Ï°Ò»Ð©¹ØÓÚXQuery µÄ»ù±¾Óï·¨¡£
We will use the following XML document in the examples below.
ÎÒÃǽ«ÔÚÏÂÃæµÄ°¸ÀýÖÐʹÓÓbooks.xml”Îĵµ£º
"books.xml":
“books.xml”ÎļþÄÚÈÝÈçÏ£º
<?xml version="1.0" encoding="ISO-8859-1"?> <bookstore> <book category="COOKING"> <book category="CHILDREN"> <book category="WEB"> <book category="WEB"> </bookstore> |
View the "books.xml" file in your browser.
ÔÚä¯ÀÀÆ÷ÖÐä¯ÀÀ“books.xml”Îļþ¡£
XQuery uses functions to extract data from XML documents.
XQuery ʹÓú¯Êý´ÓXMLÎĵµÖлñÈ¡Êý¾Ý¡£
The doc() function is used to open the "books.xml" file:
doc() º¯ÊýÓÃÓÚ´ò¿ª"books.xml"Îļþ£º
doc("books.xml")
|
XQuery uses path expressions to navigate through elements in an XML document.
XQuery ͨ¹ý·¾¶±í´ïʽ²Ù×÷XMLÎĵµÖеÄÔªËØ¡£
The following path expression is used to select all the title elements in the "books.xml" file:
ÏÂÊö·¾¶±í´ïʽÓÃÓÚÔÚ"books.xml"ÎļþÖÐÑ¡Ôñ title ÔªËØ£º
doc("books.xml")/bookstore/book/title
|
(/bookstore selects the bookstore element, /book selects all the book elements under the bookstore element, and /title selects all the title elements under each book element)
£¨/bookstore Ñ¡Ôñ bookstoreÔªËØ£»/book Ñ¡Ôñ bookstore ÔªËØÏµÄËùÓÐ book ÔªËØ£»/title Ñ¡Ôñÿ¸öbook ÔªËØÏµÄËùÓÐtitleÔªËØ¡£
The XQuery above will extract the following:
ÉÏÊöµÄXQuery»á»ñÈ¡ÏÂÊöÄÚÈÝ£º
<title lang="en">Everyday Italian</title> |
XQuery uses predicates to limit the extracted data from XML documents.
XQuery ʹÓÃÌõ¼þνÓïÏî¸ø´ÓXMLÎļþÖÐժȡµÄÊý¾Ý¸½¼ÓÒ»¸öÌõ¼þ¡£
The following predicate is used to select all the book elements under the bookstore element that have a price element with a value that is less than 30:
ÏÂÃæµÄÌõ¼þνÓïÏîÊÇÓÃÀ´Ñ¡Ôñ bookstore ÔªËØÏ price ÔªËØÖµÐ¡ÓÚ30µÄËùÓÐ book ÔªËØµÄ±í´ïʽ£º
doc("books.xml")/bookstore/book[price<30]
|
The XQuery above will extract the following:
ÉÏÊöXQueryÓï¾ä»á»ñÈ¡ÏÂÃæµÄÄÚÈÝ£º
<book category="CHILDREN"> |
ÆÀÂÛ (0)
All