Question

How do I replace line breaks within a specific XML node?

E.g.: ^J to <br/> within <content:encoded></content:encoded>

Sample of the code:

    <content:encoded><![CDATA[
      Communities across the Northwest Territories have harvested a bumper crop

      of produce ranging from potatoes and carrots to spinach and lettuce thanks to

      dedicated community gardeners and the Government of the Northwest Territories’ (GNWT).
    ]></content:encoded>
Was it helpful?

Solution

If there's only one such range, the following will do:

/<content:encoded>/,/<\/content:encoded>/s#$#<br/>#

This executes a :substitute command over the range delimited by the (opening / closing) tags. The example adds the <br/> tag, if you want to condense everything into one line, search for \n instead of $ (\n\s* to also remove the indent).

If there are multiple such tags that you want to replace, prepend :global to the command. This will execute the substitute (this time from the current line containing the start tag to the next end tag) for all tags found in the buffer (which you can again influence by prepending a different range, e.g. 1,100global).

OTHER TIPS

Use proper XML handling tool. For example, xsh:

open file.xml ;
for my $text in //content:encoded/text() {
    my $lines = xsh:split("\n", $text) ;
    for $lines {
        my $t := insert text (.) before $text ;
        insert element br before $text ;
    }
    delete $text;
}
save :b ;

You could use a macro:

  1. qq start recording
  2. /content:encoded<cr> go to next tag. Note <cr> means hit enter.
  3. vit visually select in tag
  4. :'<,'>s/\n\s*/<br\/>/g replace all newlines followed by any number of spaces with <br/>. Note the '<,'> will automatically be added by vim.
  5. q stop recording
  6. 5@q repeat 5 times.

It's probably possible using regex too but my regex foo isnt up to that.

I think the solution is to visually select the lines, then :s#\n#<br/>\r#g - it will replace the line endings to <br/>.

If you want to replace it in every inner tag, then you shuld use: :g /<content:encoded>/;/\/content:encoded/ s#\n#<br/>\r#g

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top