对于我的XML,我有以下场景。
<content>
<para>text-1 <emphasis type="bold">text-2</emphasis> text-3</para>
</content>我想像下面这样解析它
<content>
<p>text-1 <b>text-2</b> text-3</p>
</content>我创建了XSLT,如下所示
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="xml" encoding="ISO-8859-1" indent="no"/>
<xsl:template name="para">
<p>
<xsl:value-of select="text()" disable-output-escaping="yes"/>
<xsl:for-each select="child::*">
<xsl:if test="name()='emphasis'">
<xsl:call-template name="emphasis"/>
</xsl:if>
</xsl:for-each>
</p>
</xsl:template>
<xsl:template name="emphasis">
<xsl:if test="attribute::type = 'bold'">
<b>
<xsl:value-of select="text()" disable-output-escaping="yes"/>
</b>
</xsl:if>
</xsl:template>
<xsl:template match="/">
<content>
<xsl:for-each select="content/child::*">
<xsl:if test="name()='para'">
<xsl:call-template name="para"/>
</xsl:if>
</xsl:for-each>
</content>
</xsl:template>
</xsl:stylesheet>上面提供的XSLT正在生成如下输出
<content>
<p>text-1 text-3<b>text-2 </b></p>
</content>请指导我您的建议,我怎样才能得到我想要的输出?
发布于 2011-10-14 16:32:25
为此,您只需使用特殊情况扩展标准标识转换,以匹配您的para和emphasis元素。例如,对于para元素,您可以使用以下命令将para替换为p,然后继续匹配所有子节点
<xsl:template match="para">
<p>
<xsl:apply-templates select="@*|node()"/>
</p>
</xsl:template>因此,给定以下XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<!-- This is the Identity Transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<!-- Replace para with p -->
<xsl:template match="para">
<p>
<xsl:apply-templates select="@*|node()"/>
</p>
</xsl:template>
<!-- Replace emphasis with b -->
<xsl:template match="emphasis[@type='bold']">
<b>
<xsl:apply-templates select="node()"/>
</b>
</xsl:template>
</xsl:stylesheet>当应用于以下输入XML时
<content>
<para>text-1 <emphasis type="bold">text-2</emphasis> text-3</para>
</content> 以下是输出
<content>
<p>text-1 <b>text-2</b> text-3</p>
</content>您应该能够看到,如果您输入的XML有更多要转换的标记,那么扩展到其他情况是多么容易。
发布于 2011-10-14 16:36:20
像这样做;)
<?xml version="1.0" encoding="utf-8" ?>
<xsl:stylesheet
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
<xsl:template match="content">
<content><xsl:apply-templates select="para" /></content>
</xsl:template>
<xsl:template match="emphasis [@type='bold']">
<b><xsl:value-of select="." /></b>
</xsl:template>
</xsl:stylesheet>执行此操作时,默认模板将捕获text-1和text-3
https://stackoverflow.com/questions/7763583
复制相似问题