我有以下XML文件我想使用XSLT转换为csv文件:(已修订)
<ns4:transaction xmlns:ns2="http://www.example.com/Ops" xmlns:ns4="http://www.example.com/Transaction" xmlns:ns3="http://www.example.com/vehicleDetail">
<sender>sending person</sender>
<receiver>receiving person</receiver>
<created>2016-12-31T00:00:00Z</created>
<messages>
<ns3:vehicleDetail>
<identifier>
<vehicle>Benz</vehicle>
<dayOfOrigin>2016-02-01</dayOfOrigin>
<localDayOfOrigin>2016-02-01</localDayOfOrigin>
<initialDayOfOrigin>2016-02-01</initialDayOfOrigin>
<localInitialDayOfOrigin>2016-02-01</localInitialDayOfOrigin>
</identifier>
<vehicleModified>UPD</vehicleModified>
<vehicleOperStatus>O</vehicleOperStatus>
<trip modified="UPD">
<tripNo>198866</tripNo>
</trip>
<trip modified="UPD">
<tripNo>198865</tripNo>
</trip>
</ns3:vehicleDetail>
</messages>
</ns4:transaction>
我的xslt看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:ns2="http://www.example.com/Ops" xmlns:ns4="http://www.example.com/Transaction" xmlns:ns3="http://www.example.com/vehicleDetail">
<xsl:template match="ns4:transaction">
<xsl:for-each select="messages/ns3:vehicleDetail/trip">
<xsl:value-of select="../../../created" />
<xsl:text>,</xsl:text>
<xsl:value-of select="tripNo"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
CSV文件输出应该是这样的:
2016-12-31T00:00:00Z,198866
2016-12-31T00:00:00Z,198865
我确实尝试使用带有通用命名空间处理的XSLT来解决这个问题,但我没有走得太远。有没有关于如何做的提示/提示?
*更新以反映更接近问题。
答案 0 :(得分:1)
使用格式正确的输入XML,例如:
<zero xmlns:alpha="http://example.com/alpha">
<one>
<fruit>
<apple>Red</apple>
</fruit>
<alpha:test>
<alphaA>1</alphaA>
<alphaB>2</alphaB>
</alpha:test>
<alpha:test>
<alphaA>3</alphaA>
<alphaB>4</alphaB>
</alpha:test>
</one>
<one>
<fruit>
<apple>Blue</apple>
</fruit>
<alpha:test>
<alphaA>5</alphaA>
<alphaB>6</alphaB>
</alpha:test>
<alpha:test>
<alphaA>7</alphaA>
<alphaB>8</alphaB>
</alpha:test>
</one>
</zero>
这将是相当微不足道的:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns1="http://example.com/alpha">
<xsl:output method="text" encoding="UTF-8" />
<xsl:template match="/zero">
<xsl:for-each select="one/ns1:test">
<xsl:value-of select="../fruit/apple"/>
<xsl:text>,</xsl:text>
<xsl:for-each select="*">
<xsl:value-of select="."/>
<xsl:if test="position()!=last()">
<xsl:text>,</xsl:text>
</xsl:if>
</xsl:for-each>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
要处理修改后的输入,样式表应如下所示:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns4="http://www.example.com/Transaction"
xmlns:ns3="http://www.example.com/vehicleDetail">
<xsl:output method="text" encoding="UTF-8" />
<xsl:template match="ns4:transaction">
<xsl:for-each select="messages/ns3:vehicleDetail/trip">
<xsl:value-of select="../../../created" />
<xsl:text>,</xsl:text>
<xsl:value-of select="tripNo"/>
<xsl:text> </xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
请注意添加的xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
声明(没有样式表不是样式表)以及输出方法设置为文本。