使用XSLT将XML转换为CSV,通过属性值关联元素



我正在尝试使用XSLT将XML转换为CSV。CSV中的值来自/data/messValue/r(读数(,其中每个读数通过";p〃;"的属性;r〃;标签(参见下面的示例(。我只想要measTypes的一个子集,在下面的例子中只有op1-op4(我不在乎op5(。我认为XSLT是将其转换为CSV的正确方法,但我不确定如何将读取值与正确的measType关联起来。另外,我是XSLT的新手,所以我正在学习很多新概念。

输入:

<data type="A">
<measType p="1">op1</measType>
<measType p="3">op2</measType>
<measType p="4">op3</measType>
<measType p="6">op4</measType>
<measType p="7">op5</measType>
<measValue label="label1">
<r p="1">100</r>
<r p="3">200</r>
<r p="4">150</r>
<r p="6">50</r>
<r p="7">300</r>
</measValue>
</data>

所需输出(带表头(:

label,op1,op2,op3,op4
label1,100,200,150,50

此外,如果缺少一个操作,我希望在CSV中输出一个空字段(或零值(。

例如,如果op2不在XML中,那么输出应该是这样的:

label,op1,op2,op3,op4
label1,100,,150,50

伪逻辑

template for data
apply-templates for measType
template for measType
Find p value corresponding to op1 and apply-templates for r with matching p value
Find p value corresponding to op2 and apply-templates for r with matching p value
Find p value corresponding to op3 and apply-templates for r with matching p value
Find p value corresponding to op4 and apply-templates for r with matching p value
template for r
print value

我可以使用XSLT1.0(通过xsltproc(或2.0(通过saxonb-XSLT(。

使用密钥,也许只使用

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="xs">
<xsl:param name="types" as="xs:string*" select="'op1', 'op2', 'op3', 'op4'"/>

<xsl:output method="text"/>

<xsl:key name="type" match="measType" use="@p"/>
<xsl:template match="data">
<xsl:value-of select="'label', $types" separator=","/>
<xsl:text>&#10;</xsl:text>
<xsl:apply-templates select="measValue"/>
</xsl:template>

<xsl:template match="measValue">
<xsl:value-of select="@label, r[key('type', @p)[. = $types]]" separator=","/>
<xsl:text>&#10;</xsl:text>
</xsl:template>
</xsl:stylesheet>

它将输出正确的r值,尽管顺序取自measValue内的序列,而不是基于measType顺序。对于你的样品来说,这似乎无关紧要。

对于订单和您的额外要求,将value-of更改为

<xsl:value-of select="@label, for $t in $types return string(r[key('type', @p)[. = $t]])" separator=","/>

最新更新