[xquery-talk] replacing a node in in-memory XML

Robert Walpole robert.walpole at devon.gov.uk
Tue Nov 13 10:27:04 PST 2007

Just to complete the thread, I have now got this working exactly as I wanted using a modification of the code provided by Wolfgang. Here is the complete function:

declare function local:replaceServices($cg as node()) as node()
    typeswitch ($cg)
        case $elem as element(services) return (: if the element is a services element return the following :)
                template:populateTemplateElement($elem, true())
        case $elem as element() return (: if the element is anything else just return it as it is - with child nodes intact :) 
           element { node-name($elem) } {
                $elem/@*, for $child in $elem/node() return local:replaceServices($child)
        default return $cg
The $cg node is my in-memory node which contains the services element I want to replace. The function template:populateTemplateElement already existed so it was much easier for me to use this method than to go down the XSLT route, which would've meant starting all over.
The template:populateTemplateElement function basically compares the atomic values that exist in the record with all of the possible values specified in the schema. It then returns elements containing all of the possible atomic values from the schema with the addition of value attribute containing an xs:boolean stating whether or not the group has this value.
The true() parameter passed to the function is simply to tell the function whether to return "Yes"/"No" in the value attrib or "true"/"false". In this case I want "Yes"/"No".
Thanks again for all your suggestions and some very interesting comments.
Rob Walpole
Devon Portal Developer
Web: http://www.devonline.gov.uk
Email: robert.walpole at devon.gov.uk


From: Wolfgang Meier [mailto:wolfgangmm at gmail.com]
Sent: Tue 06/11/2007 15:31
To: Robert Walpole
Cc: talk at xquery.com
Subject: Re: [xquery-talk] replacing a node in in-memory XML

Hi Robert,

> I am trying to figure out the best way to replace a node within an in-memory
> XML fragment.

I really like to use the typeswitch statement for things like this:

declare function t:replace($node as node()) as node() {
    typeswitch ($node)
        case $elem as element(services) return
                <service value="false">1</service>
                <service value="true">2</service>
                <service value="false">3</service>
        case $elem as element() return
           element { node-name($elem) } {
                $elem/@*, for $child in $elem/node() return t:replace($child)
        default return $node



-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://x-query.com/pipermail/talk/attachments/20071113/0554d48b/attachment.htm

More information about the talk mailing list