我正在寻找一些提示,获取Cdata元素的字符串长度
<root>
<description><![CDATA[This handbook covers the major topics <b>in</b> Spanish, but is by no means complete.]]></description>
</root>
我尝试过这样做,我正在使用 XSLT 1.0
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xlink="http://www.w3.org/1999/xlink">
<xsl:variable name="Values">
<xsl:value-of select="root/description" disable-output-escaping="yes"/>
</xsl:variable>
<xsl:value-of select="string-length($Values)"/>
</xsl:stylesheet>
总字符串长度 85 它包括<b></b>
,但除<b></b>
外我需要79。
请让我有一些想法。
答案 0 :(得分:1)
抱歉,但是78:
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:template match="description">
<xsl:call-template name="string-length" />
</xsl:template>
<xsl:template name="string-length">
<xsl:param name="string" select="." />
<xsl:param name="length" select="0" />
<xsl:choose>
<xsl:when test="string-length($string) = 0">
<xsl:value-of select="$length" />
</xsl:when>
<xsl:when test="not(contains($string, '<'))">
<xsl:value-of select="$length + string-length($string)" />
</xsl:when>
<xsl:otherwise>
<xsl:variable
name="before"
select="string-length(substring-before($string, '<'))" />
<xsl:call-template name="string-length">
<xsl:with-param name="string"
select="substring-after($string, '>')" />
<xsl:with-param name="length"
select="$length + $before" />
</xsl:call-template>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
这不会处理<
,而不是>
。
现在进行讲座:
<![CDATA[...]]>
不是元素。正确的术语是&#34; CDATA部分&#34;。请参阅https://www.w3.org/TR/xml/#sec-cdata-sect 答案 1 :(得分:0)
要干净利落地执行此操作,您需要切换到支持XPath 3 parse-xml-fragment
(https://www.w3.org/TR/xpath-functions-30/#func-parse-xml-fragment)的处理器,例如
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:math="http://www.w3.org/2005/xpath-functions/math"
exclude-result-prefixes="xs math"
version="3.0">
<xsl:template match="/">
<xsl:value-of select="string-length(parse-xml-fragment(root/description))"/>
</xsl:template>
</xsl:stylesheet>
需要当前版本的Saxon 9或AltovaXML或Exselt。