【发布时间】:2015-04-14 12:10:33
【问题描述】:
我是 XSLT 的新手。我浏览了这个论坛中的不同解决方案,但我的问题有点不同。假设我们有一个 xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Transaction>
<operation>DEBIT</operation>
<autoRegistration>true</autoRegistration>
<allowRecurrence>true</allowRecurrence>
<network>VISA</network>
<source>RANDOM</source>
<origin>
<merchant>ABC</merchant>
<transactionId>1234</transactionId>
<channel>SINGLE</channel>
<country>DE</country>
</origin>
<customer>
<number>338317</number>
<eMail>someone@somewhere.de</eMail>
<dateOfBirth>1975-06-15</dateOfBirth>
<contact>
<eMail>someone@somewhere.de</eMail>
<phoneNumbers></phoneNumbers>
</contact>
<clientInfo>
<ip>123.111.123.123</ip>
<userAgent>Mozilla/5.0 (Windows NT 6.2; WOW64)</userAgent>
<acceptHeader>*/*</acceptHeader>
</clientInfo>
</customer>
</Transaction>
假设我需要使用 XSLT 将其转换为 CSV。我需要我的 CSV,如下所示:
operation,allowRecurrence,source,merchant
DEBIT,true,RANDOM,ABC
嵌套的 xml 元素越多,现实世界的问题就越复杂。我应该如何为这样的问题设计我的 XSLT,以便它处理多层嵌套的 XML 元素并为我准备一个 CSV。 到目前为止,我已经设法整理:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:variable name="delimiter" select="','"/>
<!-- define an array containing the fields we are interested in -->
<xsl:variable name="fieldArray">
<field>operation</field>
<field>allowRecurrence</field>
<field>source</field>
<field>merchant</field>
</xsl:variable>
<xsl:param name="fields" select="document('')/*/xsl:variable[@name='fieldArray']/*"/>
<xsl:template match="/">
<xsl:variable name="currNode" select="."/>
<!-- output the header row -->
<xsl:for-each select="$fields">
<xsl:if test="position() != 1">
<xsl:value-of select="$delimiter"/>
</xsl:if>
<xsl:value-of select="."/>
</xsl:for-each>
<!-- output newline -->
<xsl:text>
</xsl:text>
<xsl:for-each select="$fields" >
<xsl:if test="position() != 1">
<xsl:value-of select="$delimiter"/>
</xsl:if>
<xsl:value-of select="$currNode/*/*[name() = current()]"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
我被困在 <xsl:value-of select="$currNode/*/*[name() = current()]"/> 的逻辑上...我如何在这个循环中改变 XML 元素嵌套的级别。
【问题讨论】: