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>
Some other easy steps to achieve this;
Used W3cschools editor to try out.
Sample XML File :
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<catalog>
<cd>
<disk id="title"><![CDATA[Sample xml]]></disk >
<disk id="artist"><![CDATA[Vijay]]></disk >
</cd>
</catalog>
Sample XSL file :
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="/catalog/cd/disk[@id='title']"/></td>
<td><xsl:value-of select="/catalog/cd/disk[@id='artist']"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Final result is;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With