How to add attribute to all particular children of a node

99封情书 提交于 2019-12-05 18:39:24

First, let me point out that there is a difference in how this is done for just in-memory use versus updating the content of the database. For the latter, you could do:

for $add in $test//add
return
  xdmp:node-insert-child(
    $add, 
    attribute atta1 { 1 }
  )

To change it in memory, which is what functx does, you'll be making a copy of the original, making changes in the copy as you build it. This is called recursive descent and is a pretty common pattern. I wrote a blog post a while ago that shows how to implement recursive descent, but essentially you'll do a typeswitch that, when it encounters an "add" element, creates the new attribute. You can use the functx function for that. Something along these lines (untested):

declare function local:change($node) 
{ 
  typeswitch($node) 
    case element(add) return 
      functx:add-attributes($node, xs:QName('att1'), 1)
    case element() return 
      element { fn:node-name($node) } { 
        $node/@*, 
        $node/node() ! local:change(.)
      } 
    default return $node 
};

This code assumes that an add element won't have add elements inside of it; if you will, then you'd want to do something like the second case for the first.

Well you can replace/insert/delete an element or attribute in two ways. In-memory change or changing the actual content of the database. Since you do not want to change the value in DB, you can use in-memory document updation.

import module namespace mem = "http://xqdev.com/in-mem-update" at "/MarkLogic/appservices/utils/in-mem-update.xqy";

Instead of using xdmp:node-insert-child() you can use mem:node-insert-child(<x/>, <y/>)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!