Martin Eve
Martin Eve

Reputation: 2751

XPath: select an element with more than 3 comments

I am trying to select an element whose text contains more than 3 comments with a specific value.

I have tried:

//*[count(self::comment()[. = "comment_text"]) > 3]

and

//*[count(comment()[. = "comment_text"]) > 3]

and variations of that with no success. What am I doing wrong?

Any help much appreciated.

Upvotes: 0

Views: 174

Answers (2)

Linga Murthy C S
Linga Murthy C S

Reputation: 5432

and just in case the version of xslt is 1.0 and the way you have used, use the below expression:

//*[count(comment()[. = 'comment_text']) > 3]

Upvotes: 0

Mathias Müller
Mathias Müller

Reputation: 22647

Your approach works with XSLT 2.0 - you did not say which version you are working with.

However, it is common practice to escape the > character to gt and you must pay attention to nested quotes (quotes must be single if nested inside double quotes and vice versa).

Sample Input XML

<?xml version="1.0" encoding="utf-8"?>

<root>
   <true><!--comment_text--><!--comment_text--><!--comment_text--><!--comment_text--></true>
   <wrong1><!--comment_text--><!--comment_text--><!--comment_text--></wrong1>
   <wrong2><!--comment_text--><!--comment_text--><!--comment_text--><!--wrong_text--></wrong2>
</root>

Stylesheet

<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:output method="xml" indent="yes"/>
   <xsl:strip-space elements="*"/>

   <xsl:template match="/">
      <xsl:apply-templates/>
   </xsl:template>

   <xsl:template match="*[count(comment()[.='comment_text']) gt 3]">
      <xsl:copy/>
   </xsl:template>

</xsl:stylesheet>

Output

<?xml version="1.0" encoding="UTF-8"?>
<true/>

Upvotes: 2

Related Questions