【问题标题】:How to create a table-of-contents with all levels of hierarchy?如何创建具有所有层次结构的目录?
【发布时间】:2010-08-12 17:15:06
【问题描述】:

给定以下 XML 文档:

<Include>
  <Feature Title="A">
    <Feature Title="1" />
    <Feature Title="2" />
  </Feature>
  <Feature Title="B">
    <Feature Title="3">
      <Feature Title="i" />
      <Feature Title="ii" />
    </Feature>
    <Feature Title="4" />
  </Feature>
</Include>

我需要生成一个如下所示的文本文件:

; Header

A
A/1
A/2
B
B/3
B/3/i
B/3/ii
B/4

我最好的尝试是 XSL 样式表:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text" omit-xml-declaration="yes" />
  <xsl:strip-space elements="*" />

  <xsl:template match="/">
    <xsl:text>; Header&#x0A;&#x0D;&#x0A;&#x0D;</xsl:text>
    <xsl:apply-templates select="//Feature" /></xsl:template>

  <xsl:template match="Feature">
    <xsl:value-of select="@Title" /><xsl:text>&#x0A;&#x0D;</xsl:text>
  </xsl:template>
</xsl:stylesheet>

但这正在生成输出:

; Header

A
1
2
B
3
i
ii
4

如何让所有层次的层次都出现在输出中?

【问题讨论】:

    标签: xslt


    【解决方案1】:

    这个样式表:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:output method="text"/>
        <xsl:template match="Include">
            <xsl:text>; Header&#xA;&#xA;</xsl:text>
            <xsl:apply-templates/>
        </xsl:template>
        <xsl:template match="Feature">
            <xsl:param name="pPrevious" select="''"/>
            <xsl:value-of select="concat($pPrevious,@Title,'&#xA;')"/>
            <xsl:apply-templates>
                <xsl:with-param name="pPrevious" select="concat($pPrevious,@Title,'/')"/>
            </xsl:apply-templates>
        </xsl:template>
    </xsl:stylesheet>
    

    输出:

    ; Header
    
    A
    A/1
    A/2
    B
    B/3
    B/3/i
    B/3/ii
    B/4
    

    只是为了好玩,一行 XPath 2.0:

    concat('; Header&#xA;&#xA;',
           string-join(/Include//Feature/string-join(
                ancestor-or-self::Feature/@Title,'/'),
               '&#xA;')
          )
    

    【讨论】:

    • 完美!感谢您的解决方案。
    • @Brian Bassett:不客气!我很高兴它有帮助。
    猜你喜欢
    • 1970-01-01
    • 2019-10-27
    • 2017-09-20
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多