我有XML数据,我需要使用xsl转换将其转换为CSV。但问题是,XML根节点(参考A,B,C节点)会有所不同。请参阅以下内容:
XML data
--------
<Sheets>
<A>
<Data>
<Row>
<value1>2</value1>
<value2>4</value2>
</Row>
<Row>
<value1>5</value1>
<value2>6</value2>
</Row>
</Data>
</A>
<B>
<Data>
<Row>
<value1>12</value1>
<value2>13</value2>
</Row>
<Row>
<value1>14</value1>
<value2>15</value2>
</Row>
</Data>
</B>
<C>
<Data>
<Row>
<value1>1</value1>
<value2>1</value2>
</Row>
<Row>
<value1>2</value1>
<value2>2</value2>
</Row>
</Data>
</C>
</Sheets>
CSV output should like this: ---------------------------- A, 2, 4 A, 5, 6 B, 12, 13 B, 14, 15 C, 1, 1 C, 2, 2
请帮帮我。
提前致谢。
答案 0 :(得分:3)
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:output omit-xml-declaration="yes" indent="no" method="text" />
<xsl:template match="/Sheets">
<xsl:for-each select="*">
<xsl:variable name="dataSet" select="name()" />
<xsl:for-each select="Data/Row">
<xsl:value-of select="$dataSet" />
<xsl:text>, </xsl:text>
<xsl:for-each select="*">
<xsl:value-of select="text()" />
<xsl:if test="position() != last()">
<xsl:text>, </xsl:text>
</xsl:if>
</xsl:for-each>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
答案 1 :(得分:1)
这应该输出你想要的文字:
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/Sheets">
<!-- This will match the letters -->
<xsl:for-each select="*">
<xsl:for-each select="*/descendant::Row">
<xsl:text>
</xsl:text>
<!-- Name of grand parent (two levels up) which is the letter -->
<xsl:value-of select="local-name(../..)"/><xsl:for-each select="*">, <xsl:value-of select="."/>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>