tags:

views:

167

answers:

6

How do I delete comments in XML?

If the opening and the closing comment tags are on the same line, I use :g/^<!--.*-->$/d to delete the comment. How to delete the comments that are spread across many lines?

+1  A: 

You should use XSLT to transform the file to a new file. You use the identity transform with an additional rule to not copy over the comments.

<xsl:template match="node()|@*">
   <xsl:copy>
     <xsl:apply-templates select="@*"/>
     <xsl:apply-templates/>
   </xsl:copy>
 </xsl:template>

<xsl:template match="comment()"/>

You can use "xsltproc" in the libxslt package on Linux to do this as a script which I imagine you can execute from vim.

Dave
A: 

I believe this should work:

:g/<!--.*?-->/d

The question mark makes the asterisk "lazy" instead of "greedy", meaning it will match as little as possible to satisfy the expression. This prevents the expression from removing the middle part of this example:

We want to keep this<!-- This is a comment -->We also want to keep this<!-- Another comment -->

EDIT: Looks like the vim flavor of regex doesn't support *? lazy matching. My bad.

Kaivosukeltaja
what about multi line ?
ghostdog74
A: 

if its not too much of a hassle and you have gawk on your system. you can try this

$ more file
<!--
asdlfj
sdjf
;jsgsdgjasl -->
text i want
i want
....
<!-- junk junk -->
i want text
anthor text
end

$ gawk -vRS='-->' '{ gsub(/<!--.*/,"")}1' file


text i want
i want
....


i want text
anthor text
end
ghostdog74
can you please explain the "1" at the end of the gsub() call?
Vijay Dev
you can write another way: gawk -vRS='-->' '{ gsub(/<!--.*/,"")}{print}' file
ghostdog74
+10  A: 

\_. instead of . allows matching on all characters including newlines. But that alone will cause the regex engine to go overboard since regexes are greedy by default. Use \{-} instead of * for a non-greedy match all.

Since the g/ /d command only deletes a single line (even for a multiline match), it would be preferable to switch to s/ / /g (substitute global).

:%s/<!--\_.\{-}-->//g

fengb
That worked great! Thanks!
Vijay Dev
A: 

Can i get help with annswering a similar question of mine

jack
What is the question? I don't see you asking any questions before.
Vijay Dev
+1  A: 

G'day,

Doesn't entering

da>

delete the comment when the cursor is placed somewhere within the comment block?

You have to have a vim with textobjects enabled at compile time. Entering:

:vers

will let you see if textobjects are enabled in your build.

There's a lot of these funky text selections. Have a look at the relevant page in the docs.

Edit: You might have to add

set matchpairs+=<:>

to your .vimrc for this to work.

HTH

cheers,

Rob Wells
da> does work. Can you tell how to repeat this through out the file?
Vijay Dev
@Vijay, sorry mate I have no idea. You might have to use the original regexp suggested.
Rob Wells