You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求提供Apache FreeMarker实现CSV转XML的示例(含模板与Java代码)

Hey there! Let's walk through a practical example of converting CSV to XML using Apache FreeMarker. I'll cover both the template setup and core Java code to tie it all together.

1. Prerequisite: Add Dependencies

First, make sure you have the Apache FreeMarker library in your project. If you're using Maven, add this to your pom.xml:

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.32</version> <!-- Use the latest stable version available -->
</dependency>

For Gradle users, add this to your build.gradle:

implementation 'org.freemarker:freemarker:2.3.32'

2. FreeMarker Template (csv-to-xml.ftl)

Create a .ftl template file that defines how your CSV data translates to XML. This example assumes your CSV has a header row, with each subsequent row representing a single data entry.

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <entries>
        <#list csvData as entry>
        <entry>
            <#list entry?keys as key>
                <${key}>${entry[key]?xml}</${key}>
            </#list>
        </entry>
        </#list>
    </entries>
</data>

Quick Template Breakdown:

  • <?xml version="1.0" encoding="UTF-8"?>: Standard XML declaration to set encoding and version.
  • <#list csvData as entry>: Loops through every row in our parsed CSV data (where csvData is a list of maps, each map linking header names to row values).
  • <${key}>${entry[key]?xml}</${key}>: Dynamically creates XML elements for each CSV column. The ?xml built-in automatically escapes special characters like <, >, or & to keep your XML valid.

3. Java Implementation

Here's the Java code to read the CSV, parse it into a FreeMarker-compatible data model, and render the template to generate XML output.

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CsvToXmlConverter {

    public static void main(String[] args) throws IOException, TemplateException {
        // 1. Initialize FreeMarker configuration
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_32);
        // Point to the directory where your .ftl templates are stored
        cfg.setDirectoryForTemplateLoading(new File("src/main/resources/templates"));
        cfg.setDefaultEncoding("UTF-8");

        // 2. Load the pre-defined template
        Template template = cfg.getTemplate("csv-to-xml.ftl");

        // 3. Parse the input CSV into a structured data model
        List<Map<String, String>> csvData = parseCsvFile("src/main/resources/data.csv");

        // 4. Prepare the data model to pass to FreeMarker
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("csvData", csvData);

        // 5. Generate and write XML output (you can also print to console if needed)
        Writer outputWriter = new FileWriter("output.xml");
        template.process(dataModel, outputWriter);

        // Clean up resources
        outputWriter.close();
        System.out.println("XML file generated successfully!");
    }

    private static List<Map<String, String>> parseCsvFile(String csvFilePath) throws IOException {
        List<Map<String, String>> csvData = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new FileReader(csvFilePath));

        // Read the header row to get column names
        String[] headers = reader.readLine().split(",");

        String line;
        while ((line = reader.readLine()) != null) {
            String[] values = line.split(",");
            Map<String, String> rowMap = new HashMap<>();

            // Map each value to its corresponding header (trim whitespace for cleanliness)
            for (int i = 0; i < headers.length; i++) {
                rowMap.put(headers[i].trim(), values[i].trim());
            }
            csvData.add(rowMap);
        }

        reader.close();
        return csvData;
    }
}

Code Explanation:

  • FreeMarker Configuration: We set up the configuration to locate our template files and define default encoding.
  • CSV Parsing: The parseCsvFile method reads the CSV, extracts headers, and maps each row's values to the corresponding header names, storing everything in a list of maps.
  • Template Processing: We feed the parsed CSV data into the template's data model, then process the template to write the final XML to a file.

Example Input CSV (data.csv):

id,name,email,role
1,John Doe,john@example.com,Developer
2,Jane Smith,jane@example.com,Designer

Example Output XML (output.xml):

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <entries>
        <entry>
            <id>1</id>
            <name>John Doe</name>
            <email>john@example.com</email>
            <role>Developer</role>
        </entry>
        <entry>
            <id>2</id>
            <name>Jane Smith</name>
            <email>jane@example.com</email>
            <role>Designer</role>
        </entry>
    </entries>
</data>

Important Notes:

  • This basic CSV parser splits by commas directly. For complex CSVs with quoted fields or commas inside values, use a dedicated library like OpenCSV or Apache Commons CSV instead of manual splitting.
  • Always use the ?xml built-in in your template to escape special characters—this prevents invalid XML output.

内容的提问来源于stack exchange,提问作者E. Xue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:46:42