Style replacement = attributes with tags in XHTML via XSLT

Let's say that on the XHTML page there is the following:

<span style="color:#555555; font-style:italic">some text</span> 

How can I change this:

 <span style="color:#555555;"><em>some text</em></span> 
+2
source share
2 answers

This is not as simple as it seems, since XSLT is not the best tool for parsing strings - but this is exactly what you need to get the contents of the style attribute in a general way.

However, depending on the complexity of your input, something like this may be enough (I tried to be as general as possible):

 <!-- it a good idea to build most XSLT around the identity template --> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*" /> </xsl:copy> </xsl:template> <!-- specific templates over general ones with complex if/choose inside --> <xsl:template match="span[ contains(translate(@style, ' ', ''), 'font-style:italic') ]"> <xsl:copy> <xsl:copy-of select="@*" /> <xsl:attribute name="style"> <!-- this is pretty assumptious - might work, might break, depending on how complex the @style value is --> <xsl:value-of select="substring-before(@style, 'font-style')" /> <xsl:value-of select="substring-after(@style, 'italic')" /> </xsl:attribute> <em> <xsl:apply-templates select="node()" /> </em> </xsl:copy> </xsl:template> 
+2
source

Just for fun, more general XSLT 2.0 solutions (can be optimized):

 <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*"/> </xsl:copy> </xsl:template> <xsl:template match="span[tokenize(@style,';')[ matches(.,'\p{Z}*font\-style\p{Z}*:\p{Z}*italic\p{Z}*') ]]"> <xsl:copy> <xsl:apply-templates select="@* except @style"/> <xsl:attribute name="style" select= "tokenize(@style,';')[not( matches(.,'\p{Z}*font\-style\p{Z}*:\p{Z}*italic\p{Z}*') )]" separator=";"/> <em> <xsl:apply-templates select="node()"/> </em> </xsl:copy> </xsl:template> </xsl:stylesheet> 

Output:

 <span style="color:#555555"><em>some text</em></span> 
+2
source

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


All Articles