I have edited the problem to make it clear. I want to fetch all the section nodes with their section nodes and title node included,keeping the nested level.Below is the output result I wanted:
<?xml version="1.0" encoding="UTF-8"?>
<results>
<section id="intro" difficulty="easy">
<title>Introduction</title>
<section>
<title>Web Data and the Two Cultures</title>
</section>
</section>
<section id="syntax" difficulty="medium">
<title>A Syntax For Data</title>
<section>
<title>Base Types</title>
</section>
<section>
<title>Representing Relational Databases</title>
</section>
<section>
<title>Representing Object Databases</title>
</section>
</section>
</results>
And the xml content like this:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="book.xsl"?>
<book>
<title>Data on the Web</title>
<author>Serge Abiteboul</author>
<author>Peter Buneman</author>
<author>Dan Suciu</author>
<section id="intro" difficulty="easy">
<title>Introduction</title>
<p>Text ... </p>
<section>
<title>Web Data and the Two Cultures</title>
<p>Text ... </p>
<figure height="400" width="400">
<title>Traditional client/server architecture</title>
<image source="csarch.gif"/>
</figure>
<p>Text ... </p>
</section>
</section>
<section id="syntax" difficulty="medium">
<title>A Syntax For Data</title>
<p>Text ... </p>
<figure height="200" width="500">
<title>Graph representations of structures</title>
<image source="graphs.gif"/>
</figure>
<p>Text ... </p>
<section>
<title>Base Types</title>
<p>Text ... </p>
</section>
<section>
<title>Representing Relational Databases</title>
<p>Text ... </p>
<figure height="250" width="400">
<title>Examples of Relations</title>
<image source="relations.gif"/>
</figure>
</section>
<section>
<title>Representing Object Databases</title>
<p>Text ... </p>
</section>
</section>
</book>
Here is my solution,which is wrong:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/book">
<xsl:apply-templates select="section"/>
</xsl:template>
<xsl:template match="section">
<xsl:element name="section">
<xsl:for-each select="@*">
<xsl:attribute name="{name()}"><xsl:value-of select="."/></xsl:attribute>
</xsl:for-each>
</xsl:element>
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="section"/>
</xsl:template>
<xsl:template match="title">
<xsl:element name="title">
<xsl:for-each select="@*">
<xsl:attribute name="{name()}"><xsl:value-of select="."/></xsl:attribute>
</xsl:for-each>
<xsl:value-of select="."/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
I was thinking about using a recursion, but I didn't find how to do that in XSLT. There should be other ways. Thanks in advance!