Home > XQuery Resources > XQuery Tutorial> Constructors
This section demonstrates a few variations of construction of elements, attributes, PIs etc in queries.

 
{-- construct an element using the direct element
    constructor syntax (XML notation) and with constant
    values

    As you can see when only constant values are used for
    content, an element constructor is pretty much
    well-formed XML

    A later example demonstrates the creation of XML with
    this very same structure using the computed constructor
    syntax --}

<book isbn="isbn-0060229357">
    <title>Harold and the Purple Crayon</title>
    <author>
        <first>Crockett</first>
        <last>Johnson</last>
    </author>
</book>





{-- construct an element using the computed element
    constructor syntax and with constant values --}

element book
{
    attribute isbn { "isbn-0060229357" },
    element title { "Harold and the Purple Crayon"},
    element author
    {
        element first { "Crockett" },
        element last { "Johnson" }
    }
}





{-- Example of computed element constructor demonstrating
    language translation.

    This example is demonstrated with only a single entry of
    the dictionary. The dictionary could be an XML document
    with entries for different english words and their
    translations in different languages. The tags can be
    translated from english to any other supported language
    using a simple query along these lines --}

let $dict := <entry word="address">
    <variant lang="German">Adresse</variant>
    <variant lang="Italian">indirizzo</variant>
</entry> ,
$e := <address>123 Roosevelt Ave. Flushing, NY 11368</address>
return element { $dict/variant[@lang="Italian"]/text() } {$e/node() }





{-- Construct element dynamically with the user-id as tag
    name and the user name as its content --}

<user>
{
for $a in document("data/R-users.xml")/users/user_tuple
let $userid := $a/userid/text(), $name := $a/name/text()
return
    element {$userid} {$name}
}
</user>





{-- Construct element dynamically using name().
    Make every attribute of person a sub-element. --}

<result>
{
for $a in document("data/ref-census.xml")//person
let $node := shallow($a)
return
    element {name($node)}
    {
        # loop over all attributes
        for $attr in $node/@*
        return
          element {name($attr)}
            {string($attr)}
    }
}
</result>





# element constructor test:
# Construct PI (not supported yet)

<result>
    <? MyFormatter fontsize="20" ?>
</result>

 


Company | Products | Solutions | News & Events | Developers | Contact Us | Site Map