0

我想将 XML 文件转换为 CSV 文件。所以我只是解析 XML 文件。现在我想将此解析数据写入 CSV 文件。我不知道如何编写此解析数据。所以请帮助我

<data399173_eff_sor>
 <record>
   <ID>1</ID>
   <item_no>1.0</item_no>
   <description>Hack off tiles and make good walls</description>
   <price>100</price>
   <base_qty>50</base_qty>
   <var_qty>20</var_qty>
   <base_price_>5000</base_price_>   
 </record>
 <record>
   <ID>1</ID>
   <item_no>1.03</item_no>
   <description>Test</description>
   <price>45</price>
   <base_qty>100</base_qty>
   <var_qty>4500</var_qty>
   <base_price_>0</base_price_>
 </record>
</data399173_eff_sor>

Java代码:

public static void main(String argv[]) {         
    try {    
    File fXmlFile = new File("D:/formdata.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);        
    doc.getDocumentElement().normalize();

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());   
    NodeList nList = doc.getElementsByTagName("record");     
    System.out.println("----------------------------");  
    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);   
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {  
            Element eElement = (Element) nNode;  
            System.out.println("Item No : " + eElement.getElementsByTagName("item_no").item(0).getTextContent());
            System.out.println("Description : " + eElement.getElementsByTagName("description").item(0).getTextContent());
            System.out.println("price : " + eElement.getElementsByTagName("price").item(0).getTextContent());
            System.out.println("base qty : " + eElement.getElementsByTagName("base_qty").item(0).getTextContent());
            System.out.println("Var qty : " + eElement.getElementsByTagName("var_qty").item(0).getTextContent());
            System.out.println("Base price : " + eElement.getElementsByTagName("base_price_").item(0).getTextContent());                
        }
    }
    generateCsvFile("d:\\testCSV.csv");

    } catch (Exception e) {
    e.printStackTrace();
    }
  }

private static void generateCsvFile(String sFilename) {
    // TODO Auto-generated method stub
    try
    {
        FileWriter writer = new FileWriter(sFilename);

         writer.flush();
         writer.close();             
    }

    catch(IOException e)
    {
         e.printStackTrace();
    } 
}

所以现在如何编写这个解析数据?我只是创建 generateCsvFile() 函数来创建文件,我不知道它是从正确的地方调用的

4

1 回答 1

0

一种方法是使用 commons-csv 来写入数据。从测试代码:

 final FileWriter sw = new FileWriter("myfile.csv");
 final CSVPrinter printer = new CSVPrinter(sw, format);

 for (int i = 0; i < nLines; i++) {
     printer.printRecord(lines[i]);
 }

 printer.flush();
 printer.close()
于 2013-10-16T09:39:03.847 回答