开发者

change value of element by xquery

<category>
     <catid>1</catid>
     <cattext> sport &开发者_运维技巧lt;/cattext>
</category>

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


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.io/

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


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> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜