I am trying to get the CDATA
content of an XML node using XSL. The
node currently looks like this:
<node id="1" text="Book Information" ><![CDATA[This is sample text]]></node>
I need the This is sample text
piece. Does anyone have any idea about this?
Thanks in advance.
Well, if I use this stylesheet:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:template match="node/text()">
<xsl:copy/>
</xsl:template>
</xsl:stylesheet>
on this XML file:
<?xml version="1.0" encoding="utf-8"?>
<node id=1 text="Book Information" ><![CDATA[This is sample text]]></node>
I get a parse error, because id=1
is invalid XML.
Putting quotes around the attribute value (id="1"
) and rerunning the stylesheet, I get as output:
This is sample text
So there's a start. Basically, just treat the CDATA as a text node and you're on your way.
You said:
I found something like:
<xsl:output cdata-section-elements="text"/>
and then to fetch CDATA:
<xsl:value-of select="node" />
This approach works just fine if you're using value-of
as well. Here would be an example along the lines of your comment, using value-of
instead. Note, though, that cdata-section-elements
only works on the output side, indicating which output XML elements you want to print as CDATA sections instead of plain old character data. It doesn't have anything to do with fetching the data.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output cdata-section-elements="foo"/>
<xsl:template match="/">
<foo>
<xsl:value-of select="node"/>
</foo>
</xsl:template>
</xsl:stylesheet>
prints out
<?xml version="1.0"?>
<foo><![CDATA[This is sample text]]></foo>