tags:

views:

31

answers:

2

Hi I have structure

<category>
     <catid>1</catid>
     <cattext> sport </cattext>
</category>

I want change text of element <cattext> into another like "art" instead of sport by using xquery

+1  A: 
declare namespace local = "http://example.org";  
declare function local:copy-replace($element as element()) {  
  if ($element/self::cattext)
  then <cattext>art</cattext>
  else element {node-name($element)}  
               {$element/@*, 
                for $child in $element/node()  
                return if ($child instance of element())  
                       then local:copy-replace($child)  
                       else $child  
               }  
};  
local:copy-replace(/*)

Output:

<?xml version="1.0" encoding="UTF-8"?>
<category>
     <catid>1</catid>
     <cattext>art</cattext>
</category> 
Alejandro
+1  A: 

if your engine supports updates and scripting:

declare variable $x := 
   <category>
     <catid>1</catid>
     <cattext> sport </cattext>
   </category>;

replace value of node $x/cattext with "art";
$x;

or if you don't want to persist the changes you can transform a copy of it:

let $x := 
   <category>
     <catid>1</catid>
     <cattext> sport </cattext>
   </category>
return
   copy $changedx := $x
   modify (replace value of node $changedx/cattext with "art")
   return $changedx 

these code snippets successfully run on http://try.zorba-xquery.com

If your XQuery processor doesn't support updates Alejandro's solution is top.

Dennis Knochenwefel