Html 根据内容在XSLT中格式化输出
使用此xml片段:Html 根据内容在XSLT中格式化输出,html,xml,xslt,Html,Xml,Xslt,使用此xml片段: <paragraph><bold>Test</bold> - This <italic>word</italic> should be <underline>underlined</underline> according to xml</paragraph> Test-这个词应该根据xml加下划线 如何将此“段落”输出为HTML,同时用HTML中使用的标记替换使用的标记 我尝
<paragraph><bold>Test</bold> - This <italic>word</italic> should be <underline>underlined</underline> according to xml</paragraph>
Test-这个词应该根据xml加下划线
如何将此“段落”输出为HTML,同时用HTML中使用的标记替换使用的标记
我尝试过这个XSLT片段,但它不会打印嵌套标记之外的文本,只打印粗体、斜体和下划线之间的文本
<xsl:template match="p:paragraph">
<xsl:for-each select="./*">
<xsl:choose>
<xsl:when test="name(.)='bold'">
<xsl:apply-templates select="."/>
</xsl:when>
<xsl:when test="name(.)='italic'">
<xsl:apply-templates select="."/>
</xsl:when>
<xsl:when test="name(.)='underlined'">
<xsl:apply-templates select="."/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="./text()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
<xsl:template match="bold">
<p><b><xsl:value-of select="current()"/></b></p>
</xsl:template>
<xsl:template match="italic">
<p><i><xsl:value-of select="current()"/></i></p>
</xsl:template>
<xsl:template match="underline">
<p><u><xsl:value-of select="current()"/></u></p>
</xsl:template>
我怎样才能使模板的输出符合预期
提前感谢您的主要问题是
/*
(可以简化为只选择*
)只选择元素,但您也希望选择文本节点。所以你能做的就是把它改成这个
<xsl:for-each select="node()">
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
但是,您可以简化整个XSLT以更好地利用模板匹配。试试这个XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" indent="yes" />
<xsl:template match="paragraph">
<p>
<xsl:apply-templates />
</p>
</xsl:template>
<xsl:template match="bold">
<b>
<xsl:apply-templates />
</b>
</xsl:template>
<xsl:template match="italic">
<i>
<xsl:apply-templates />
</i>
</xsl:template>
<xsl:template match="underline">
<u>
<xsl:apply-templates />
</u>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
(显然,您需要对此进行调整以处理名称空间,因为您当前的XSLT正在选择
p:paragration
,这表明您的XML中有名称空间)。您的主要问题是/*
(可以简化为仅*
)只选择元素,但您也希望选择文本节点。所以你能做的就是把它改成这个
<xsl:for-each select="node()">
<xsl:otherwise>
<xsl:value-of select="."/>
</xsl:otherwise>
但是,您可以简化整个XSLT以更好地利用模板匹配。试试这个XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="html" indent="yes" />
<xsl:template match="paragraph">
<p>
<xsl:apply-templates />
</p>
</xsl:template>
<xsl:template match="bold">
<b>
<xsl:apply-templates />
</b>
</xsl:template>
<xsl:template match="italic">
<i>
<xsl:apply-templates />
</i>
</xsl:template>
<xsl:template match="underline">
<u>
<xsl:apply-templates />
</u>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
(显然,您需要对此进行调整以处理名称空间,因为您当前的XSLT正在选择p:paragration
,这表明您的XML中有名称空间)