I wonder if anyone can help me or point me in the right direction. I am currently having some trouble returning the right elements from an XML file. I am Simply just try to obtain a cut down version of a large XML file that I have so its outputting another XML file (not HTML which a lot of tutorials are on).
I have XML fields like:
<Field name="audio_format" value="" />
<Field name="camera" value="" />
However I have many more elements to many to list here , I have one for everything imaginable metadata that you would want to include in a Video or audio file.
So my question and problem is how do I specify in my XSL which Field names to grab , it is currently grabbing everything within the tags, which is good but its not right.Here as a bit of my XSL.
<!--MasterClip-->
<xsl:template match="MasterClip">
<MasterClip>
<xsl:apply-templates />
</MasterClip>
</xsl:template>
<xsl:template match="Field">
<Field>
<xsl:attribute name="name">
<xsl:value-of select="@name" />
</xsl:attribute>
<xsl:attribute name="value">
<xsl:value-of select="@value" />
</xsl:attribute>
</Field>
I have abou开发者_如何学编程t 50 fields then outputting , however I only want to select ones I specify (10 of them) . I have tried a few examples but most relate to searching and sorting, any help would be great. Even just a quick example showing me how to select one of them and i can just replicate it out for the rest!.
Thanks
You can use template match directly:
<xsl:template match="Field[matches(@name,'audio_format|camera')]">
<xsl:copy-of select="."/>
</xsl:template>
Where matches
is just an XSLT 2.0 function.
You can specify predicates to apply templates to:
<xsl:apply-templates select="/Field[@name='audio_format' or @name='camera']" />
This can be done quite generically using a variable that enumerates the names of the fields to be copied:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" encoding="utf-8" indent="no" />
<xsl:variable name="fields" select="'|audio_format|camera|'" />
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="MasterClip">
<xsl:copy>
<xsl:apply-templates select=
"*[contains($fields, concat('|', @name, '|'))]" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
Given this input:
<MasterClip>
<Field name="audio_format" value="" />
<Field name="camera" value="" />
<Field name="some_other_name" value="" />
</MasterClip>
Output:
<MasterClip>
<Field name="audio_format" value="" />
<Field name="camera" value="" />
</MasterClip>
Note: This example uses the identity transform to copy the Field
elements. If you don't want a direct copy, then simply create a separate template for handling those elements.
Note also: This is XSLT 1.0 compatible.
精彩评论