2011-10-14 16 views
1

我的XML有以下情況。如何使用XSLT分析嵌套標記?

<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> 

輸出請用你的建議引導我estions,我怎麼能得到我的慾望輸出?

在此先感謝!

任何建議/輸入/幫助非常感謝!

回答

1

要做到這一點,你只需要擴展特殊情況下,標準的身份轉換爲符合強調元素。例如,對於元素,你將以下與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有更多的標籤進行改造。

+0

+1一個很好的答案 –

2

像這樣做;)

<?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> 

,當你做這樣的默認模板將捕獲文本1和文本3