我们如何将XML文件转换为CSV?

问题描述:

我有一个XML文件

<?xml version="1.0" encoding="ISO-8859-1"?>
<Results>
    <Row>
        <COL1></COL1>
        <COL2>25.00</COL2>
        <COL3>2009-07-06 15:49:34.984</COL3>
        <COL4>00001720</COL4>
    </Row>
    <Row>
        <COL1>RJ</COL1>
        <COL2>26.00</COL2>
        <COL3>2009-07-06 16:04:16.156</COL3>
        <COL4>00001729</COL4>
    </Row>
    <Row>
        <COL1>SD</COL1>
        <COL2>28.00</COL2>
        <COL3>2009-07-06 16:05:04.375</COL3>
        <COL4>00001721</COL4>
    </Row>  
</Results>

我必须将此XML转换为CSV文件。我听说我们可以做这样的事情使用XSLT。我怎么能这样做在Java(有/没有XSLT)?

I have to convert this XML into CSV file. I have heard we can do such thing using XSLT. How can i do this in Java ( with/without XSLT )?

在伪代码中:

loop through the rows:
    loop through all children of `Row`:
        write out the text
        append a comma
    new line

这个快速的小循环将在每行的末尾写一个逗号,但我相信你可以弄清楚如何删除它。

That quick little loop will write a comma at the end of each line, but I'm sure you can figure out how to remove that.

为了实际解析XML,我建议使用 JDOM 。它有一个非常直观的API。

For actually parsing the XML, I suggest using JDOM. It has a pretty intuitive API.