rosebrit3
rosebrit3

Reputation: 523

Converting special characters in xml using XSLT

Am trying to convert the special characters in xml to their encoded forms using xslt.

Example:

& to & 
" to " 
< to &lt; 
> to &gt;

and so on. The code am using is given below

<?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" encoding="UTF-8"/>

<xsl:template match="/">
    <xsl:apply-templates select="//search-results/items" />
</xsl:template>

<xsl:template match="items">
    <textarea>
        <xsl:apply-templates select="file-item" />
    </textarea>
</xsl:template>


<xsl:template match="file-item">
    <xsl:apply-templates select="." mode="details"/>    
</xsl:template>


<xsl:template match="*" mode="details">
    <file-item>
        <id><xsl:value-of select = "@id"/></id>
        <xsl:copy-of select = "name"/>
        <xsl:copy-of select = "creation-date" />
        <xsl:copy-of select = "modification-date"/>
        <xsl:copy-of select = "file-info"/>
        <xsl:copy-of select = "creator"/>
        <xsl:copy-of select = "last-modifier"/>     
      </file-item>        
</xsl:template>
</xsl:stylesheet>

The XML structure is

<id>5060554</id>
<name>This is a File && and it is a "Test File" </name>
<creation-date timestamp="1487516375360">19.02.2017 14:59</creation-date>
<modification-date timestamp="1488128705695">26.02.2017 17:05</modification-date>
<file-info>
<name>Background-Wallpaper & Nature.jpg</name>
<creator user-id="2196">
<last-modifier user-id="2120">

The output should contain the xml nodes as well, and that is why am using xsl:copy of in a textarea instead of xsl:value-of. Becausse xsl:value-of select="name" will only output This is a File && and it is a "Test File" whereas xsl:copy-of will produce This is a File && and it is a "Test File"

Am using XSLT version 1.o

The desired output that am looking for is This is a File &amp; &amp; and it is a &quot;Test File&quot;

Upvotes: 1

Views: 3322

Answers (1)

Michael Kay
Michael Kay

Reputation: 163262

You say that the input XML contains

<name>This is a File && and it is a "Test File" </name>

That's a contradiction. If it contains that string, then it isn't XML. Ampersands in XML are always escaped. And if the input isn't XML, then you can't use XSLT to process it.

You say "we are converting the data to xml and then to html (UI view of the website) using XSLT." It seems you are converting the data to XML incorrectly, and you need to fix that.

Upvotes: 1

Related Questions