XSLT: How to exclude specific html tags from an xml string?

I am trying to exclude a specific set of html tags from an xml string using XSLT 1.0

Here, at present, I exclude the <a> and <img> tags. For the <a> tag, I want to display only text.

Designed XSLT Template:

 <xsl:template match="*" mode="ExcludeHTMLTags"> <xsl:choose> <xsl:when test="local-name() = 'a' or local-name() = 'img'"> <xsl:value-of select="text()"/> </xsl:when> <xsl:otherwise> <xsl:apply-templates select="node()|@*"/> </xsl:otherwise> </xsl:choose> </xsl:template> 

Call the template below:

 <xsl:variable name="guideContent"> <root> <xsl:apply-templates select="document(@guideID)/tcm:Component/tcm:Data/tcm:Content/em:GeneralContent/em:Body/node()" mode="expandXHTML"/> </root> </xsl:variable> <xsl:apply-templates select="msxsl:node-set($guideContent)/node()" mode="ExcludeHTMLTags"/> 

XML input string:

 <root> This is a test message. <p>Message within p tag</p> click <a href="www.test.com">here</a>. <img src="/test.jpg" /> Message after image. <strong>Message within strong</strong> <link:component id="XXX" ... >My Link</link:component> <p>Message after link component</p> </root> 

OUTPUT:

 <root> This is a test message. <p>Message within p tag</p> click here. Message after image. <strong>Message within strong</strong> <link:component id="XXX" ... >My Link</link:component> <p>Message after link component</p> </root> 

Please suggest what I am doing wrong and will tell you in the best way.

+4
source share
1 answer

This conversion is :

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="a"><xsl:apply-templates/></xsl:template> <xsl:template match="img"/> </xsl:stylesheet> 

when applied to this XML document (none of them provided by OP !!!):

 <html> <body> <a>Anchor text</a> <img source="http://someUrl"/> </body> </html> 

creates the desired, correct result:

 <html> <body>Anchor text</body> </html> 
+4
source

Source: https://habr.com/ru/post/1441001/


All Articles