Convert an xml element whose contents are inside CDATA
I have an xml snippet as below
<Detail uid="6"> <![CDATA[ <div class="heading">welcome to my page</div> <div class="paragraph">this is paraph</div> ]]> </Detail>and i want to change
<div class="heading">...</div> to <h1>Welcome to my page</h1> <div class="paragraph">...</div> to <p>this is paragraph</p> You know how I can do this in xslt 1.0
+7
jjennifer
source share3 answers
How to start two conversions.
Pass 1.)
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" encoding="UTF-8"/> <xsl:template match="/"> <xsl:apply-templates /> </xsl:template> <xsl:template match="Detail"> <Detail> <xsl:copy-of select="@*"/> <xsl:value-of select="." disable-output-escaping="yes" /> </Detail> </xsl:template> </xsl:stylesheet> Will produce:
<?xml version="1.0" encoding="UTF-8"?> <Detail uid="6"> <div class="heading">welcome to my page</div> <div class="paragraph">this is paraph</div> </Detail> Pass 2.)
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes" encoding="UTF-8"/> <xsl:template match="/"> <xsl:apply-templates /> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*| node()" /> </xsl:copy> </xsl:template> <xsl:template match="div[@class='heading']"> <h1><xsl:value-of select="."/></h1> </xsl:template> <xsl:template match="div[@class='paragraph']"> <p><xsl:value-of select="."/></p> </xsl:template> </xsl:stylesheet> It produces:
<?xml version="1.0" encoding="UTF-8"?> <Detail uid="6"> <h1>welcome to my page</h1> <p>this is paraph</p> </Detail> +9
Mads hansen
source shareYou cannot tell XSL 1.0 to pull a string from CDATA and parse it as XML.
+2
bmargulies
source shareYou cannot βdeleteβ CDATA, but you can achieve the desired result somewhat crudely:
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <Detail> <xsl:variable name="before" select="substring-before(//Detail,'<div class="heading">')" /> <xsl:variable name="afteropen" select="substring-after(//Detail,'<div class="heading">')" /> <xsl:variable name="body" select="substring-before($afteropen, '</div>')" /> <xsl:variable name="after" select="substring-after($afteropen, '</div>')" /> <xsl:value-of select="concat($before, '<h1>', $body, '</h1>',$after)" disable-output-escaping="yes" /> </Detail> </xsl:template> </xsl:stylesheet> This will work for the first type of div you are trying to parse, and you can follow something similar with the second. This can be made more general with some efforts.
+2
Dan
source share