xsl: xml to csv conversion - search list for value, otherwise output empty field
I have an xml structure like:
<foos>
<foo>
<foo_type>1</foo_type>
<foo_date>2011_1_1</foo_date>
</foo>
<foo>
<foo_type>1</foo_type>
开发者_C百科 <foo_date>2012_1_1</foo_date>
</foo>
<foo>
<foo_type>2</foo_type>
<foo_date>2011_1_1</foo_date>
</foo>
</foos>
What I need to do is produce one value from this, where foo_type==1 and the date is latest date. Previously I have used a sort descending for a list of dates. If there is no foo of foo_type==1 it should produce an empty field. (Fields are surrounded with quotes, comma is the delimiter.)
I was envisioning doing this by building a list of all foos of type 1. I'm not sure how to do that in xsl. something like this perhaps:
<xsl:variable name="fooList">
<xsl:for-each select="foos/foo">
<xsl:if test="contains(foo_type, '1')">
<xsl:value-of select="concat($fooList, ', ', foo_date)"/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
then i would parse the comma delimited list and sort to determine the latest date:
<xsl:variable name="latestFooDate">
<xsl:sort select="split(fooList)" order="descending" />
</xsl:variable>
and finally call the template to format the result:
<xsl:call-template name="dateFormat">
<xsl:with-param name="date" select="latestFooDate" />
</xsl:call-template>
Keep in mind this is pseudo code because I dont know how to do this. Now if someone can help turn my pseudo into the real thing.
I don't think you need to create a comma-delimited list before getting the first date. This seems like a bit of extra effort. You could sort your foo elements in your xsl:for-each statement, and then just get the first one (i.e. the one with position() = 1)
Try this template for matching a foos element
<xsl:template match="foos">
<xsl:for-each select="foo[foo_type='1']">
<xsl:sort select="foo_date" />
<xsl:if test="position() = 1">
<xsl:value-of select="foo_date" />
</xsl:if>
</xsl:for-each>
</xsl:template>
This loops over all foo elements with a foo_type of 1, but then only performs any processing on the first one.
When you use this template to match your given input XML, the output should then be
2011_1_1
You can then go ahead and perform extra date formatting on this as required.
精彩评论