How to search and replace content programmatically?

Last modified by Vincent Massol on 2017/01/29

You have 2 main options:

  • Use search/replace in a script. For example something like the following would replace the word welcome with "bienvenue" everywhere in the wiki:
    {{velocity}}
    #set ($xwql = "where doc.content like '%welcome%'")
    #foreach ($item in $services.query.xwql($xwql).execute())
      #if ($request.confirm == "1")
        #set ($itemDoc = $xwiki.getDocument($item))
        $itemDoc.setContent($itemDoc.getContent().replaceAll(
          "welcome", "bienvenue"))
        $itemDoc.save("Replaced bienvenue")
        * [[$item>>$item]] replaced!
      #else
        * [[$item>>$item]]
      #end
    #end

    [[Replace "welcome" by "bienvenue">>?confirm=1]]
    {{/velocity}}
  • Use the XWiki Syntax AST to perform more surgical replaces. For example to modify all links so that they are displayed in italics you could use something like:
    {{groovy}}
    import org.xwiki.rendering.block.*
    import org.xwiki.rendering.block.match.*
    import org.xwiki.rendering.listener.*

    def mydoc = xwiki.getDocument('Sandbox.VMA')
    def xdom = mydoc.getXDOM()

    for (Block block : xdom.getBlocks(new ClassBlockMatcher(LinkBlock.class), Block.Axes.DESCENDANT)) {
      Block parentBlock = block.getParent();
      Block newBlock = new FormatBlock(Collections.<Block>singletonList(block), Format.ITALIC);
      parentBlock.replaceChild(newBlock, block);
    }

    // Save the modified XDOM
    mydoc.setContent(xdom)
    mydoc.save('made links in italics')
    {{/groovy}}

    See the Rendering module for more details.

Tags:
Created by Vincent Massol on 2017/01/26
   

Get Connected