How do I use XSLT to add a new element in output d

2019-09-11 05:39发布

问题:

I have input document. It;s a table with one col:

<table>
<tr><td>0</td></tr>
<tr><td>1</td></tr>
<tr><td>0</td></tr>
<tr><td>3</td></tr>
<tr><td>3</td></tr>
</table>

The number in first row is number of parents of <li> elements in output document. It's variously. I need to generate structure in ouput document like this:

<li id="0">
 <li id="1">
  <li id="2"/>
 </li>
 <li id="3">
  <li id="4"/>
  <li id="5"/>
 </li>
</li>

Do I do the link to element in out-document to append child? May be I need recursion algorithm...

回答1:

I think what you could do is use a key, to associate tr elements by the first preceding sibling that has a lower td value

 <xsl:key name="lists" match="tr" use="generate-id(preceding-sibling::tr[td &lt; current()/td][1])" />

To get the top-level elements, you would do this...

<xsl:apply-templates select="key('lists', generate-id())" />

And when positioned on a tr element, to get the child elements for that, you would do this...

<xsl:apply-templates select="key('lists', generate-id())" />

Try this XSLT

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

    <xsl:key name="lists" match="tr" use="generate-id(preceding-sibling::tr[td &lt; current()/td][1])" />

    <xsl:template match="/table">
        <xsl:apply-templates select="key('lists', '')" />
    </xsl:template>

    <xsl:template match="tr">
        <li id="{td}">
            <xsl:apply-templates select="key('lists', generate-id())" />
        </li>
    </xsl:template>
</xsl:stylesheet>

I don't believe <li> tags should be nested in this way. They should really be contained in <ol> or <ul> tags, for a start. Perhaps this is what you really meant....

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

    <xsl:key name="lists" match="tr" use="generate-id(preceding-sibling::tr[td &lt; current()/td][1])" />

    <xsl:template match="/table">
        <ul>
            <xsl:apply-templates select="key('lists', '')" />
        </ul>
    </xsl:template>

    <xsl:template match="tr">
        <li id="{td}">
            <xsl:if test="key('lists', generate-id())">
                <ul>
                    <xsl:apply-templates select="key('lists', generate-id())" />
                </ul>
            </xsl:if>
        </li>
    </xsl:template>
</xsl:stylesheet>


标签: xslt