开发者

How to create a table-of-contents with all levels of hierarchy?

开发者 https://www.devze.com 2023-01-11 02:28 出处:网络
Given the following XML document: <Include> <Feature Title=\"A\"> <Feature Title=\"1\" />

Given the following XML document:

<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>

I need to generate a text file that looks like:

; Header

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

My best attempt at ach开发者_Python百科ieving this is the XSL stylesheet:

<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>

But this is generating the output:

; Header

A
1
2
B
3
i
ii
4

How do I get all levels of hierarchy to be present in the output?


This stylesheet:

<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>

Output:

; Header

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

Just for fun, one line XPath 2.0:

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

精彩评论

暂无评论...
验证码 换一张
取 消