other register

Monday, April 28, 2008

Escape <?xml version="1.0" encoding="UTF-8"?> in XML / XSLT

If an xml file is embeded in another xml file like below:

<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<name>Your name</name>

And you want to extract the embedded xml file and remove its xml declaration tag, then do the following:

<!-- Disable xml declaration by xslt -->
<xsl:output method="xml" omit-xml-declaration="yes" />

<!-- Define the string you want to remove -->
<xsl:variable name="declare">
<![CDATA[<?xml version="1.0" encoding="UTF-8"?>]]>

<!-- Get the embedded xml file -->
<xsl:variable name="prepared">
<xsl:value-of select="value" />

<!-- Remove the xml declaration and escape special characters -->
<xsl:value-of select="substring-after($prepared, $declare)"
disable-output-escaping="yes" />

No comments: