user1949832
user1949832

Reputation: 3

link xml data by element

I have the following xml file

<musicLibrary>
<compilation id="C01" title="Best of something">
    <title no="1" name="firstOne">
        <fileID>F01</fileID>
    </title>
    <title no="2" name="secondOne">
        <fileID>F02</fileID>
    </title>
    <title no="3" name="thirdOne">
        <fileID>F03</fileID>
    </title>
    <title no="4" name="fourthOne">
        <fileID>F04</fileID>
        <fileID>F05</fileID>
    </title>
</compiltion>
<compilation id="C02" title="Best of another thing">
    ...
</compilation>

<files>
    <file id="F01">
        <filename>soundFile8.mp3</filename>
        <size>3.456</size>
        <length>3.23</length>
    </file>
    <file id="F02">
        <filename>soundFile2.mp3</filename>
        <size>3.456</size>
        <length>3.23</length>
    </file>
    <file id="F03">
        <filename>soundFile7.mp3</filename>
        <size>3.456</size>
        <length>3.23</length>
    </file>
    <file id="F04">
        <filename>soundFile5.mp3</filename>
        <size>3.456</size>
        <length>3.23</length>
    </file>
    <file id="F05">
        <filename>soundFile3.mp3</filename>
        <size>3.456</size>
        <length>3.23</length>
    </file>
</files>
</musicLibrary>

Is it possible to retrieve from the file information, for example how long the playtime is of one compilation in total, by just giving the collection id? I am really stuck with this. :/ I am really missing things like joins from SQL ;)

thanks in advance!

Upvotes: 0

Views: 44

Answers (1)

wst
wst

Reputation: 11771

This can be done with an XSLT stylesheet using xpath (you can think of it as XSLT's join equivalent). In this stylesheet, the sum of the lengths for each compilation is returned:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    version="1.0">

    <xsl:template match="musicLibrary">
        <xsl:apply-templates select="compilation"/>  
    </xsl:template>

    <xsl:template match="compilation">
        <xsl:variable name="ids" select="title/fileID"/>
        <compilation id="{@id}" title="{@title}">
            <xsl:attribute name="total-length"> 
                <xsl:value-of select="sum(//files/file[@id = $ids]/length)"/>
            </xsl:attribute>
        </compilation>
    </xsl:template>

</xsl:stylesheet>

Output:

<compilation id="C01" title="Best of something" total-length="16.15"/>

Upvotes: 1

Related Questions