【发布时间】:2014-06-11 09:58:19
【问题描述】:
我正在尝试使用 Java 代码将 XML 文件动态转换为 CSV 文件。我能够获得转换为 CSV 的数据,但问题在于标题行。我需要将第一行添加到具有该列名称的 CSV 文件中。
这是Java代码:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
class xmltocsv {
public static void main(String args[]) throws Exception {
File stylesheet = new File("C:/testxsl.xsl");
File xmlSource = new File("C:/test.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xmlSource);
StreamSource stylesource = new StreamSource(stylesheet);
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(stylesource);
Source source = new DOMSource(document);
Result outputTarget = new StreamResult(new File("c:/output.csv"));
transformer.transform(source, outputTarget);
}
}
这是我的示例 XML:
<record>
<column name="ID">537316</column>
<column name="TYPE">MANUAL</column>
<column name="SECONDID" />
<column name="KEY">345</column>
</record>
这是我的 XSL 文件:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/*">
<xsl:for-each select="*[1]/*">
<xsl:value-of select="name()"/>
<xsl:if test="position() != last()">, </xsl:if>
<xsl:if test="position() = last()">
<xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
<xsl:apply-templates/>
</xsl:template>
<xsl:output method="text" encoding="iso-8859-1"/>
<xsl:param name="fieldNames" select="'yes'" />
<xsl:strip-space elements="*" />
<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()"><xsl:value-of select="normalize-space(.)"/>, </xsl:if>
<xsl:if test="position() = last()"><xsl:value-of select="normalize-space (.)"/><xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
样本输出应该是:
ID,TYPE,SECONDID,KEY\n
537316,MANUAL,,345\n
问题是,XML文件是数据库输出,会动态变化,所以需要动态获取标签名。
Here using <xsl:value-of select="name()"/>
我将标签名称作为 ID、TYPE 等的列插入。 除了 name() 之外还有其他方法可以让我从 XML 中获取正确的标签名称。
【问题讨论】: