如何对元素中的文本应用更改而不丢失其子元素。
例如:
我有这个xml,我想对“p”元素中的文本应用更改....
<section>
<p >Awesome LO</p>
<p >
Begin with an interesting fact, thought-provoking
<keyword>question</keyword>
<context>
<p type="Key Words Head">Banana</p>
<p type="Key Words">A tasty treat to eat any time, and good with ice cream – a banana split.</p>
</context>, or a one sentence scenario to illustrate why the learning object (content) is important.
</p>
<p >
Begin with a definition, if required. Then, provide an example by example view.
</p>
</section>
所以我的xsl看起来像这样......
<xsl:template match="p">
<xsl:copy>
<xsl:call-template name="widont-title">
<xsl:with-param name="text" select="text()" />
</xsl:call-template>
</xsl:copy>
</xsl:template>
问题在于,当我这样做时,我丢失了“关键字”,“上下文”以及“p”中的其他元素。任何人都能指出我的任何线索吗?谢谢!
<!-- this method puts a non breaking space in the last word of a 'p' if its less than 5 characters-->
<xsl:template name="widont-title">
<xsl:param name="temp"/>
<xsl:param name="text"/>
<xsl:param name="minWidowLength" select="5"/>
<xsl:choose>
<xsl:when test="contains($text, ' ')">
<xsl:variable name="prev" select="substring-before($text,' ')"/>
<xsl:variable name="before" select="concat($temp,' ',$prev)"/>
<xsl:variable name="after" select="substring-after($text, ' ')"/>
<xsl:choose>
<xsl:when test="contains($after, ' ')">
<xsl:call-template name="widont-title">
<xsl:with-param name="temp" select="$before"/>
<xsl:with-param name="text" select="$after"/>
</xsl:call-template>
</xsl:when>
<xsl:when test="not(contains($after, ' ')) and string-length(translate($after,'`~!@#$%^\*()-_=+\\|]}[{;:,./?<>','')) < $minWidowLength">
<xsl:value-of select="concat($before, ' ', $after)" />
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="concat($before, ' ', $after)" />
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
答案 0 :(得分:5)
目前尚不清楚 widont-title
模板的作用以及是否正确实现(看起来有点过于复杂),但问题在于此模板很快就会被应用,不会留下p
处理儿童元素的任何可能性。
解决方案(使用 identity template 并覆盖p/text()
个节点)非常简单:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="p/text()">
<xsl:call-template name="widont-title">
<xsl:with-param name="text" select="." />
</xsl:call-template>
</xsl:template>
<!-- "widont-title" template omitted for brevity -->
</xsl:stylesheet>
在提供的XML文档上应用上述转换时,任何p
元素的子元素都正确显示在输出中。