Reputation: 175
I already have an input XML
<tutorial>
<lessons>
<lesson>
chapter1 unit 1 page1
</lesson>
<lesson>
unit 1
</lesson>
</lessons>
</tutorial>
The output should be
<Geography>
<historical>
<social>
<toc1>
<toc>
<chapter>
chapter1
<chapter>
<unit>
unit 1
</unit>
<pages>
page1
</pages>
</toc>
</toc1>
<social>
</historical>
actually i am getting confused here
<lesson>
chapter1 unit 1 page1
</lesson>
<lesson>
unit 1
</lesson>
here i need two outpus
for the first lesson i need it as above output
for the second lesson i need it as output like below
<historical>
<social>
<toc1>
<toc>
<unit>
unit 1
</unit>
<toc>
</toc1>
<social>
</historical>
but sometimes i will get both type in xml i am totally confused how to do this.
can any one guide me here it can be in both XSLT1.0 and XSLT2.0
Regards Karthic
Upvotes: 0
Views: 162
Reputation: 243599
This XSLT 2.0 transformation:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="vNames" select="'chapter', 'unit', 'pages'"/>
<xsl:template match="lessons">
<Geography>
<historical>
<social>
<toc1>
<xsl:apply-templates/>
</toc1>
</social>
</historical>
</Geography>
</xsl:template>
<xsl:template match="lesson[matches(., '(chapter\s*\d+)?\s+(unit\s*\d+)\s+(page\s*\d+)?')]">
<xsl:analyze-string select="."
regex="(chapter\s*\d+)?\s+(unit\s*\d+)\s+(page\s*\d+)?">
<xsl:matching-substring>
<toc>
<xsl:for-each select="1 to 3">
<xsl:if test="regex-group(current())">
<xsl:element name="{$vNames[current()]}">
<xsl:sequence select="regex-group(current())"/>
</xsl:element>
</xsl:if>
</xsl:for-each>
</toc>
</xsl:matching-substring>
</xsl:analyze-string>
</xsl:template>
</xsl:stylesheet>
when applied on the provided XML document:
<tutorial>
<lessons>
<lesson>
chapter1 unit 1 page1
</lesson>
<lesson>
unit 1
</lesson>
</lessons>
</tutorial>
produces the wanted, correct result:
<Geography>
<historical>
<social>
<toc1>
<toc>
<chapter>chapter1</chapter>
<unit>unit 1</unit>
<pages>page1</pages>
</toc>
<toc>
<unit>unit 1</unit>
</toc>
</toc1>
</social>
</historical>
</Geography>
Explanation:
Proper use of XSLT 2.0 Regular expression capabilities such as:
The <xsl:analyze-string>
and <xsl:matching-substring>
instrunctions.
The regex-group()
function.
Upvotes: 1