How to translate a flat XML structure into hierarc

2019-08-30 01:02发布

Starting from an exemplary, ungainly formatted XML structure:

<list>
    <topic>
        <title>
            Paragraph 1
        </title>
    </topic>
    <topic>
        <main>
            Content 1
        </main>
    </topic>
    <topic>
        <main>
            Content 2
        </main>
    </topic>
    <!-- ... -->
    <topic>
        <main>
            Content n
        </main>
    </topic>
    <topic>
        <title>
            Paragraph 2
        </title>
    </topic>
    <topic>
        <main>
            Content 1
        </main>
    </topic>
    <!-- ... -->
    <topic>
        <main>
            Content n
        </main>
    </topic>
</list>

The contents of "title" and "main" are merely placeholders. The content of "title" is different in every node. The content of "main" may or may not vary. The number of "main" elements is indefinite.

The goal is to summarize the topic / main elements following a topic / title element as follows:

<list>
    <paragraph name="1">
        <item>Content 1</item>
        <item>Content 2</item>
        <item>Content n</item>
    </paragraph>
    <paragraph name="2">
        <item>Content 1</item>
        <item>Content n</item>
    </paragraph>
</list>

Boundary condition is the restriction to version 1 of xslt and xpath.

This question has been asked in similar form before. I did not find a satisfactory answer.

1条回答
Viruses.
2楼-- · 2019-08-30 01:33

Basically, you're looking for an XSLT 1.0 implementation of group-starting-with. This can be done as following:

XSLT 1.0

<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:strip-space elements="*"/>

<xsl:key name="topic-by-leader" match="topic[main]" use="generate-id(preceding-sibling::topic[title][1])" />

<xsl:template match="/list">
    <xsl:copy>
        <xsl:for-each select="topic[title]">
            <paragraph name="{position()}">
                <xsl:for-each select="key('topic-by-leader', generate-id())" >
                    <item>
                        <xsl:value-of select="normalize-space(main)" />
                    </item>
                </xsl:for-each>
            </paragraph>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
查看更多
登录 后发表回答