XSLT和嵌套元素

时间:2012-11-29 23:12:16

标签: html xslt xhtml

鉴于下面的XSL模板和XML,这里是我想要实现的HTML输出(或多或少):

<p>
foo goes here
  <span class="content"><p>blah blah blah</p><p>blah blah blah</p></span>
bar goes here
  <span class="content">blah blah blah blah blah blah</span> 
</p>

以下是实际渲染的内容(缺少&lt; span.content&gt;的全部内容):

<p>
foo goes here
  <span class="content"></span>
bar goes here
  <span class="content">blah blah blah blah blah blah</span> 
</p>

这是我的模板(摘录):

 <xsl:template match="note[@type='editorial']">
   <span class="content">
     <xsl:apply-templates />
   </span>
 </xsl>
 <xsl:template match="p">
   <p>
     <xsl:apply-templates />
   </p>
 </xsl>

这是我的xml:

<p>
foo goes here
  <note type="editorial"><p>blah blah blah</p><p>blah blah blah</p></note>
bar goes here
  <note type="editorial">blah blah blah blah blah blah</note> 
</p>

渲染特定元素并不重要。即。我不在乎是否&lt; p&gt;或者&lt; div&gt;或者&lt; span&gt;只要没有文本元素丢失,它就会被渲染。 我想避免创建一个匹配“p / note / p”的特定规则,假设&lt; note&gt; element可以包含任意子项。

我是xsl的总菜鸟,所以任何额外的提示或指示都会非常有用。

提前致谢。

3 个答案:

答案 0 :(得分:1)

您应该使用apply-templates代替apply-template

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="note[@type='editorial']">
        <span class="content">
            <xsl:apply-templates/>
        </span>
    </xsl:template>
    <xsl:template match="p">
        <p>
            <xsl:apply-templates />
        </p>
    </xsl:template>
 </xsl:stylesheet>

答案 1 :(得分:1)

好的,所以我只是在四处乱窜,这是我最终提出的解决方案。

嵌套&lt; p&gt;标签只是不起作用。您的浏览器不喜欢它们,XSLT也不喜欢它们。所以,我把所有东西都改成了&lt; divs&gt;和&lt; spans&gt;

另外,我在模板的末尾添加了几个catch-all模板。

这是适合我的目的的最终版本:

<xsl:template match="note[@type='editorial']">
   <span class="content">
     <xsl:apply-templates />
   </span>
</xsl:template>

<xsl:template match="p">
  <div class="para">
    <xsl:apply-templates />
  </div>
</xsl:template>

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

<xsl:template match="text()">
  <xsl:value-of select="." />
</xsl:template>

H / T:

http://www.dpawson.co.uk/xsl/sect2/defaultrule.html

How can xsl:apply-templates match only templates I have defined?

答案 2 :(得分:0)

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
    <xsl:apply-templates select="p"/>
    </xsl:template>
    <xsl:template match="p">
    <p>
    <xsl:apply-templates/>
    </p>
    </xsl:template>
    <xsl:template match="span">
     <note type="editorial">
     <xsl:choose>
     <xsl:when test="child::*">
     <xsl:copy-of select="child::*"/>
     </xsl:when>
     <xsl:otherwise>
                <xsl:value-of select="."/>
    </xsl:otherwise>
    </xsl:choose>
    </note>
    </xsl:template>
    <xsl:template match="text()">
    <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>
相关问题