Aggiunta di elementi e attributi XQuery

Documento di esempio XML

Continueremo a utilizzare il documento "books.xml" nei nostri esempi seguenti (lo stesso file XML utilizzato nei capitoli precedenti).

Visualizza il file "books.xml" nel tuo browser.

Aggiungere elementi e attributi ai risultati

Come visto nella sezione precedente, possiamo referenziare gli elementi e gli attributi del file di input nei risultati:

for $x in doc("books.xml")/bookstore/book/title
order by $x
return $x

L'espressione XQuery sopra menzionata cita l'elemento title e l'attributo lang nel seguente modo:

<title lang="en">Everyday Italian</title>
<title lang="en">Harry Potter</title>
<title lang="en">Learning XML</title>
<title lang="en">XQuery Kick Start</title>

L'espressione XQuery sopra menzionata restituisce l'elemento title nello stesso modo in cui è descritto nel documento di input.

Ora dobbiamo aggiungere i nostri elementi e attributi ai risultati!

Aggiungi elementi HTML e testo

Ora, dobbiamo aggiungere elementi HTML ai risultati. Metteremo i risultati in un elenco HTML:

<html>
<body>
<h1>Bookstore</h1>
<ul>
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return <li>{data($x/title)}. Categoria: {data($x/@category)}</li>
}
</ul>
</body>
</html>

L'espressione XQuery sopra menzionata genererà i seguenti risultati:

<html>
<body>
<h1>Bookstore</h1>
<ul>
<li>Everyday Italian. Categoria: COOKING</li>
<li>Harry Potter. Categoria: CHILDREN</li>
<li>Learning XML. Categoria: WEB</li>
<li>XQuery Kick Start. Categoria: WEB</li>
</ul>
</body>
</html>

Aggiungi attributi agli elementi HTML

Quindi, dobbiamo utilizzare l'attributo category come proprietà class dell'elenco HTML:

<html>
<body>
<h1>Bookstore</h1>
<ul>
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return <li class="{data($x/@category)}">{data($x/title)}</li>
}
</ul>
</body>
</html>

L'espressione XQuery sopra menzionata può generare i seguenti risultati:

<html>
<body>
<h1>Bookstore</h1>
<ul>
<li class="COOKING">Everyday Italian</li>
<li class="CHILDREN">Harry Potter</li>
<li class="WEB">Learning XML</li>
<li class="WEB">XQuery Kick Start</li>
</ul>
</body>
</html>