我有下面的XML代码XSLT处裂开子节点
<para>Lorem ipsum <link>dolor</link> sit amet</para>
,我想转换到
<para>Lorem ipsum </para><link>dolor</link><para> sit amet</para>
换句话说:我想para元素的位置进行分割链接元素在哪里。有没有提示?
我有下面的XML代码XSLT处裂开子节点
<para>Lorem ipsum <link>dolor</link> sit amet</para>
,我想转换到
<para>Lorem ipsum </para><link>dolor</link><para> sit amet</para>
换句话说:我想para元素的位置进行分割链接元素在哪里。有没有提示?
这个样式表:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*|node()[1]"/>
</xsl:copy>
<xsl:apply-templates select="following-sibling::node()[1]"/>
</xsl:template>
<xsl:template match="para">
<xsl:copy>
<xsl:apply-templates select="@*|node()[1]"/>
</xsl:copy>
<xsl:apply-templates select="link" mode="copy"/>
<xsl:apply-templates select="following-sibling::node()[1]"/>
</xsl:template>
<xsl:template match="para/link"/>
<xsl:template match="para/link" mode="copy">
<xsl:copy>
<xsl:apply-templates select="@*|node()[1]"/>
</xsl:copy>
<para>
<xsl:apply-templates select="following-sibling::node()[1]"/>
</para>
</xsl:template>
</xsl:stylesheet>
输出:
<para>Lorem ipsum </para><link>dolor</link><para> sit amet</para>
注意:细粒度遍历。
编辑:紧凑代码:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="node()|@*" name="identity">
<xsl:copy>
<xsl:apply-templates select="@*|node()[1]"/>
</xsl:copy>
<xsl:apply-templates select="self::para/link" mode="copy"/>
<xsl:apply-templates select="following-sibling::node()[1]"/>
</xsl:template>
<xsl:template match="para/link"/>
<xsl:template match="para/link" mode="copy">
<xsl:call-template name="identity"/>
</xsl:template>
<xsl:template match="node()[preceding-sibling::node()[1]
/self::link/parent::para]">
<para>
<xsl:call-template name="identity"/>
</para>
</xsl:template>
</xsl:stylesheet>
节点'para'被复制而不是生成?如果它具有属性呢?
该转化:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="no"/>
<xsl:strip-space elements="*"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/*">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="para/text()">
<para><xsl:copy-of select="."/></para>
</xsl:template>
</xsl:stylesheet>
当所提供的XML文档施加:
<para>Lorem ipsum <link>dolor</link> sit amet</para>
产生想要的,正确的结果:
<para>Lorem ipsum </para><link>dolor</link><para> sit amet</para>
请注意:
使用身份规则的每一个节点复制原样。
身份规则的带有模板的首要用于处理仅特定节点
极其简单性和功率从使用1和2的上方跟随。
嗨Dimitre,非常感谢您提供了非常优雅的解决方案,但我有一个问题,
@Roman:您可以编辑您的问题并显示您的XML的真实结构,然后确定我会修改我的答案以匹配我尚未见过的XML结构。这里没有人是clairevoyant。 :) – 2010-11-22 13:37:33
好问题,+1。看到我的答案是一个完整的,非常简短的解决方案。 :) – 2010-11-18 16:28:00