Search code examples
xmlxsltxpathxslt-1.0xquery

How to handle '<BR/>' element and convert string in new paragraph


In the below example we are trying to handle 'BR' element under the 'P' element and convert into the seprate paragraph using 'XSLT 1.0':

Can anyone help.

INPUT XML:

<?xml version="1.0" encoding="UTF-8"?>
<CONTENT>
<P>A. 05° 55’ 47.81” S – 106° 32’ 10.76” E<BR/>B. 05° 55’ 47.81” S – 106° 34’ 10.76” E<BR/>C. 05° 55’ 47.81” S – 106° 36’ 10.76” E<BR/>D. 05° 57’ 47.81” S – 106° 32’ 10.76” E<BR/>E. 05° 57’ 47.81’’S – 106° 34’ 10.76’’E<BR/>F. 05° 57’ 47.81’’S – 106° 36’ 10.76’’E<BR/>G. 05° 59’ 47.81’’S – 106° 32’ 10.76’’E<BR/>H. 05° 59’ 47.81’’S – 106° 34’ 10.76’’E<BR/>I. 05° 59’ 47.81’’S – 106° 36’ 10.76’’E</P>
</CONTENT>

EXPECTED OUTPUT:

<?xml version="1.0" encoding="UTF-8"?>
<CONTENT>
<P>A. 05° 55’ 47.81” S – 106° 32’ 10.76” E</P>
<P>B. 05° 55’ 47.81” S – 106° 34’ 10.76” E</P>
<P>C. 05° 55’ 47.81” S – 106° 36’ 10.76” E</P>
<P>D. 05° 57’ 47.81” S – 106° 32’ 10.76” E</P>
<P>E. 05° 57’ 47.81’’S – 106° 34’ 10.76’’E</P>
<P>F. 05° 57’ 47.81’’S – 106° 36’ 10.76’’E</P>
<P>G. 05° 59’ 47.81’’S – 106° 32’ 10.76’’E</P>
<P>H. 05° 59’ 47.81’’S – 106° 34’ 10.76’’E</P>
<P>I. 05° 59’ 47.81’’S – 106° 36’ 10.76’’E</P>
</CONTENT>

XSLT CODE:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

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

</xsl:stylesheet>

Reference Link: https://xsltfiddle.liberty-development.net/bEJbVso/1


Solution

  • Try this:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet 
      version="1.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
      >
      
      <xsl:template match="P[BR]">
        <p><xsl:value-of select="BR[1]/preceding-sibling::text()"/></p>
        <xsl:apply-templates select="BR"/>
      </xsl:template>
      
      <xsl:template match="P/BR[following-sibling::BR]">
        <p><xsl:value-of select="following-sibling::BR[1]/preceding-sibling::node()[1][self::text()]"/></p>
      </xsl:template>
    
      <xsl:template match="P/BR[not(following-sibling::BR)]">
        <p><xsl:value-of select="following-sibling::text()"/></p>
      </xsl:template>
    
      <xsl:template match="node()|@*">
          <xsl:copy>
              <xsl:apply-templates select="node()|@*"/>
          </xsl:copy>
      </xsl:template>
    
    </xsl:stylesheet>