02.06.2013 Views

XML Demystified

XML Demystified

XML Demystified

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

142<br />

<strong>XML</strong> Demystifi ed<br />

The function declaration statement must have a prefix, a function name, a<br />

parameter list, and a return value. In addition, a function declaration statement must<br />

also define a code block that contains statements that are executed when the function<br />

is called from within an XQuery.<br />

Here’s the structure of a function declaration statement:<br />

declare function prefix:function_name($parameter as datatype, ...)<br />

as returntype<br />

{<br />

... code for the function goes here...<br />

};<br />

Let’s declare a function. You’ll call it convertdate and it will convert the date<br />

format 2006-10-04 to October 4, 2006. The prefix will be called local. The parameter<br />

is the date that will be converted and the return value is the converted date.<br />

Here’s the function declaration. Notice that the parameter is placed within<br />

parentheses. You’ll need to give the parameter a name and specify its data type.<br />

The name is always prefaced with a $ symbol. You’ll also need to specify the data<br />

type of the value returned by the function. The return type in this example is a<br />

string.<br />

The code block is defined with open and closed French braces ({ }). This is<br />

where you place statements that execute each time the function is called. The<br />

function begins by assigning all the months to an array called $month. An array is<br />

a variable that can have many values. Next, the month-from-date() function is called<br />

to extract the month of the date and assign it to the $month variable. The day-fromdate()<br />

function and year-from-date() function are passed to the concat() function in<br />

the return clause to return the reformatted date.<br />

The function declaration statement must appear at the top of the XQuery, as we<br />

show in the following example. Think of this as defining the function before you<br />

call the function within the XQuery. The function is called later in the XQuery<br />

{local:convertdate(xs:date($cd/date))}.<br />

declare function local:convertdate($date as xs:date) as xs:string<br />

{<br />

let $months := ("January","February","March","April","May",<br />

"June","July","August","September","October","November","December")<br />

let $month := $months[month-from-date($date)]<br />

return<br />

concat($month, " ", string(day-from-date($date)), ", ",<br />

string(year-from-date($date)))<br />

};<br />

<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!