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:
    #set ($xwql = "where doc.content like '%welcome%'")
    #foreach ($item in $services.query.xwql($xwql).execute())
      #if ($request.confirm == "1")
        #set ($itemDoc = $xwiki.getDocument($item))
          "welcome", "bienvenue"))
        $"Replaced bienvenue")
        * [[$item>>$item]] replaced!
        * [[$item>>$item]]

    [[Replace "welcome" by "bienvenue">>?confirm=1]]
  • 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:
    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)'made links in italics')

    See the Rendering module for more details.

Created by Vincent Massol on 2017/01/26

Get Connected