【问题标题】:Copy first N nodes and their children with XSLT使用 XSLT 复制前 N 个节点及其子节点
【发布时间】:2020-10-09 20:14:58
【问题描述】:

我有一个包含 CD 目录的 XML 文档:

<?xml version="1.0"?>
<catalog>
  <cd><title>Greatest Hits 1999</title><artits>Various Artists</artist></cd>
  <cd><title>Greatest Hits 2000</title></cd>
  <cd><title>Best of Christmas</title></cd>
  <cd><title>Foo</title></cd>
  <cd><title>Bar</title></cd>
  <cd><title>Baz</title></cd>
  <!-- hundreds of additional <cd> nodes -->
</catalog>

我想使用 XSLT 1.0 创建此 XML 文档的摘录,其中仅包含第一个 N 个 &lt;cd&gt; 节点,以及它们的父节点和子节点。假设N=2;这意味着我希望得到以下输出:

<?xml version="1.0"?>
<catalog>
  <cd><title>Greatest Hits 1999</title><artits>Various Artists</artist></cd>
  <cd><title>Greatest Hits 2000</title></cd>
</catalog>

我找到了this answer,我从中改编了以下样式表:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>

  <xsl:param name="count" select="2"/>

  <!-- Copy everything, except... -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <!-- cd nodes that have a too large index -->
  <xsl:template match="cd[position() &gt;= $count]" />

</xsl:stylesheet>

当我尝试应用此样式表时,出现以下错误:Forbidden variable: position() &gt;= $count
当我将$count 替换为文字2 时,输出包含完整的输入文档,其中包含数百个&lt;cd&gt; 节点。

如何使用 XSLT 从我的 XML 文档中获取仍然有效的 XML 的摘录,但只是抛出了一堆节点?我正在寻找一种通用的解决方案,它也适用于不像我的示例那样简单的文档结构。

【问题讨论】:

    标签: xml xslt xslt-1.0


    【解决方案1】:

    为什么不简单:

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
    <xsl:param name="count" select="2"/>
    
    <xsl:template match="/catalog">
        <xsl:copy>
            <xsl:copy-of select="cd[position() &lt;= $count]"/>
        </xsl:copy>
    </xsl:template>
    
    </xsl:stylesheet>
    

    如果您想让它通用(这在实践中很少起作用,因为 XML 文档有多种结构),请尝试以下操作:

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
    <xsl:param name="count" select="2"/>
    
    <xsl:template match="/*">
        <xsl:copy>
            <xsl:copy-of select="*[position() &lt;= $count]"/>
        </xsl:copy>
    </xsl:template>
    
    </xsl:stylesheet>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多