2015-09-05 26 views
1

我想按顺序在'fomula'元素下面获取文本节点和元素节点,将XML转换为HTML。 我显示下面的XML代码。文本不固定。 (我再次写了代码)如何使用xsl获取文本节点?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<root> 
    <section> 
     <formula> 
      m=12n 
      <superscript> 
       2 
      </superscript> 
      +3(3n 
      <superscript> 
       2 
      </superscript> 
      +2) 
     </formula> 
     <xxx> 
      abc 
     </xxx> 
     <formula> 
      c=a+b 
      <superscript> 
       4 
      </superscript> 
     </formula> 
    </section> 
</root> 

我应该怎么写XSL才能得到下面的结果?

<p>m=12n<span>2</span>+3(3n<span>2</span>+2</p> 
<p>abc</p> 
<p>c=a+b<span>4</span></p> 

当我得到特定的元素节点时,我通常会写下如下所示的XSL。但我不知道如何依次使用同胞元素节点来获取文本节点。 请给我建议。 (我更详细地再次写的代码。)

<xsl:template match="/"> 
    <html> 
     --omitted-- 
     <body> 
      <xsl:apply-templates select="/root/section" /> 
     </body> 
    <html> 
</xsl:template> 
<xsl:template match="section"> 
    <xsl:for-each select="*"> 
     <xsl:if test="name()='formula'"> 
      <xsl:apply-templates select="." /> 
     </xsl:if> 
     <xsl:if test="name()='xxx'"> 
      <xsl:apply-templates select="." /> 
     </xsl:if> 
    </xsl:for-each> 
</xsl:template> 
<xsl:template match="formula"> 
    <p> 
     <xsl:apply-templates select="." /> 
    </p> 
</xsl:template> 
<xsl:template match="xxx"> 
    <p> 
     <xsl:apply-templates select="." /> 
    </p> 
</xsl:template> 
+0

如果您编写'test =”name()='aaa'“',这与'test = aaa'相同,不需要获取名称的字符串值。但更好的是,如答案所示,不要使用这些带有节点的'xsl:if'构造,它们会混乱你的代码,而且是不必要的。只需使用'xsl:apply-templates'(另请参阅Rubens的回答),只有在找到匹配的节点时才起作用。 – Abel

+0

谢谢您的建议。我很高兴知道使用“测试”的简单方法。但我仍然困惑。我很高兴,如果你检查我重写的代码。 – tara

+0

你的'xsl:for-each'将会遍历所有的孩子,你的'xsl:if'只适用于孩子'fomula'和'xxx'(并且仍然用'name()='nodename''来测试,只是'nodename')。你可以用一个''替换整个'xsl:for-each'及其内容,这与你现在的效果完全相同。 – Abel

回答

3

你应该看看到xsl:templatexsl:apply-templates

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 

    <xsl:template match="/"> 
     <xsl:apply-templates select="/root/section"/> 
    </xsl:template> 

    <xsl:template match="formula | xxx"> 
     <p> 
     <xsl:apply-templates /> 
     </p> 
    </xsl:template> 

    <xsl:template match="superscript"> 
     <span> 
     <xsl:apply-templates /> 
     </span> 
    </xsl:template> 

</xsl:stylesheet> 

你可以看到一个working example here

编辑:一种可能的方法是为您需要的每种特定格式创建一个模板。所以:

  • “每次我找到一个formulaxxx元素,我将附上很p元素含量时间”,“每次我找到一个superscript元素的时候,我会附上很span内容元素“
+0

谢谢您的建议。我是否需要为“公式”和“上标”准备模板?例如) tara

+0

在我的示例中,我使用这些模板来更轻松地在xslt输出中格式化特定标记;你还需要在这里做什么? –

+0

对不起。我可能误解你以前的答案。我有点困惑,我更详细地重写了代码。我很高兴,如果你再次给我你的建议。 – tara