【问题标题】:How can I write an XSLT that will recursively include other files?如何编写将递归包含其他文件的 XSLT?
【发布时间】:2010-05-25 18:19:44
【问题描述】:

假设我有一系列这种格式的 xml 文件:

A.xml:

<page>
    <header>Page A</header>
    <content>blAh blAh blAh</content>
</page>

B.xml:

<page also-include="A.xml">
    <header>Page B</header>
    <content>Blah Blah Blah</content>
</page>

使用这个 XSLT:

<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/page">
        <h1>
            <xsl:value-of select="header" />
        </h1>
        <p>
            <xsl:value-of select="content" />
        </p>
    </xsl:template>
</xsl:stylesheet>

我可以把A.xml变成这个:

<h1>
    Page A
</h1>
<p>
    blAh blAh blAh
</p>

但是我怎样才能让它也把B.xml变成这个呢?

<h1>
    Page B
</h1>
<p>
    Blah Blah Blah
</p>
<p>
    blAh blAh blAh
</p>

我知道我需要在某个地方使用document(concat(@also-include,'.xml')),但我不确定在哪里。


哦,问题是,如果 B 包含在第三个文件 C.xml 中,我需要它仍然可以工作。

你知道怎么做吗?

【问题讨论】:

  • 我怀疑你不能完全在 XSL 中做到这一点,但我已经收藏了这个问题,看看我是否错了。
  • 我觉得用递归模板应该是可以的。

标签: xml xslt recursion file-inclusion


【解决方案1】:

有可能:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:template match="page">
    <h1>
      <xsl:value-of select="header"/>
    </h1>
    <p>
      <xsl:apply-templates select="." mode="content"/>
    </p>
  </xsl:template>

  <xsl:template match="page" mode="content">
    <xsl:value-of select="content"/>
    <xsl:if test="@include">
      <xsl:apply-templates select="document(@include)" mode="content"/>
    </xsl:if>
  </xsl:template>

</xsl:stylesheet>

【讨论】:

  • 我认为mode 属性可能是我想要的。让我在我的场景中测试一下
  • 好吧,这个推动力还不够大。我的例子过于简化了。你能看看this更难的问题吗?
猜你喜欢
  • 1970-01-01
  • 2011-12-17
  • 2021-12-22
  • 1970-01-01
  • 2020-05-23
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
相关资源
最近更新 更多