【问题标题】:change value of element by xquery通过 xquery 更改元素的值
【发布时间】:2010-10-06 16:11:05
【问题描述】:
<category>
     <catid>1</catid>
     <cattext> sport </cattext>
</category>

我想通过使用 xquery 将元素 &lt;cattext&gt; 的文本更改为另一个类似“艺术”而不是运动的文本

【问题讨论】:

  • 你使用什么数据库?或者您可能只是想转型?

标签: xml xquery


【解决方案1】:

如果您的引擎支持更新和脚本:

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

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

或者如果您不想保留更改,您可以转换它的副本:

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 

这些代码sn-ps在http://try.zorba.io/上成功运行

如果您的 XQuery 处理器不支持更新,Alejandro 的解决方案是首选。

【讨论】:

    【解决方案2】:
    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(/*)
    

    输出:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      相关资源
      最近更新 更多