RE: [xsl] splitting multiple occurrences of an element within another element

Subject: RE: [xsl] splitting multiple occurrences of an element within another element
From: "Passin, Tom" <tpassin@xxxxxxxxxxxx>
Date: Wed, 24 Sep 2003 14:17:36 -0400
[Brian Benson]
> > 
> I am trying to convert an xml file that looks like this
> ====================
> <database>
>      <document form='formname'>
>           <noteinfo unid='abc'/>
>           <doclink document='1'/>
>           <doclink document='2'/>
>      </document>
> </database>
> 
> Into an xml file that looks like this
> =====================
> </database>
>      <document>
>           <form>formname</form>
>           <unid>abc</unid>
>           <doclink>1</doclink>
>      </document>
> 
>      <document>
>           <form>formname</form>
>           <unid>abc</unid>
>           <doclink>2</doclink>
>      </document>
> </database>
> 

There is no one right way to do this.  I think it is simplest to start
from the main discriminant that you have, which is the doclink.  Each
doclink is to get its own containing element.  The fact that the
container is called "document" and there is also a "document" element in
the source is just a coincidence - don't be driven by it.  

 I would just apply-templates to a node set consisting of the doclinks.
Given a doclink, you know where the other related pieces of information
are, so it is easy to get them. 

Here is a stylesheet that does just this -

<xsl:stylesheet version="1.0" 
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>

<xsl:variable name='documents' select='/database/document/doclink'/>

<xsl:template match="/">
<database>
	<xsl:apply-templates select='$documents'/>
</database>
</xsl:template>

<xsl:template match='doclink'>
	<document>
		<form><xsl:value-of select='../@form'/></form>
		<unid><xsl:value-of select='../noteinfo/@unid'/></unid>
		<doclink><xsl:value-of select='@document'/></doclink>
	</document>
</xsl:template>
</xsl:stylesheet>

You would not have to actually create a variable - you could put the
select expression inline - but this way makes the intent more clear.  Of
course, if any of the doclinks shows up in more than one place, you may
have to do something more complicated, depending on what you want the
result to be.

Your task here is perfectly suited to xslt.  The principles in use here
are -

1) Select a set of nodes to transform.

2) Write down the form of the desired output, specifying the location of
the data to be slotted into the results, and 

3) step back and let the processor do its work.

Cheers,

Tom P

Cheers,

Tom P

 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread