
在数据处理和系统集成中,将表格数据(如csv文件)转换为结构化的xml格式是一种常见需求。特别地,有时我们希望csv的每一行对应一个xml元素,而该行的各个列数据则作为该xml元素的属性而非子元素。例如,将以下csv数据:
Col1,Col2,Col3,Col4,Col5 All,0,,0,0 All,935,231,0,30 None,1011,257,0,30
转换为如下XML格式:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<row col1="All" col2="0" col3="" col4="0" col5="0"></row>
<row col1="All" col2="935" col3="231" col4="0" col5="30"></row>
<row col1="None" col2="1011" col3="257" col4="0" col5="30"></row>
</root>传统的基于DOM(Document Object Model)的Java API(如DocumentBuilder和Transformer)虽然可以构建XML,但在将CSV列动态映射为XML属性时,代码会变得相对复杂且容易出错,尤其是在处理大量属性或需要灵活结构时。本文将介绍如何利用Java Architecture for XML Binding (JAXB) 这一强大的工具,以更简洁、声明式的方式实现这一转换。
JAXB (Java Architecture for XML Binding) 是Java SE平台的一部分(Java 9+版本可能需要额外依赖),它提供了一种将Java对象与XML文档相互映射的机制。JAXB的核心优势在于,通过在Java类上使用特定的注解,可以声明性地定义Java对象如何序列化为XML(marshalling)以及如何从XML反序列化为Java对象(unmarshalling)。这种方式大大简化了XML处理的复杂性,提高了开发效率和代码可读性。
要使用JAXB将CSV数据转换为属性化XML,首先需要定义一个或多个Plain Old Java Object (POJO) 类,这些类将代表XML的结构。对于上述需求,我们需要两个POJO:一个用于表示整个XML的根元素(<root>),另一个用于表示每一行数据(<row>元素及其属性)。
立即学习“Java免费学习笔记(深入)”;
我们将创建一个Root类作为XML的顶级容器,它包含一个RowData对象的列表。RowData类将包含对应CSV列的字段,并通过JAXB注解将其映射为XML属性。
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
/**
* Represents the root element <root> of the XML document.
* Contains a list of RowData objects.
*/
@XmlRootElement(name = "root")
@XmlAccessorType(XmlAccessType.FIELD) // JAXB will access fields directly
public class Root {
// @XmlElementWrapper(name = "rows") // If you want an intermediate <rows> element
@XmlElement(name = "row") // Each item in the list will be a <row> element
private List<RowData> rows;
public Root() {
this.rows = new ArrayList<>();
}
public void addRow(RowData row) {
this.rows.add(row);
}
public List<RowData> getRows() {
return rows;
}
public void setRows(List<RowData> rows) {
this.rows = rows;
}
}
/**
* Represents a single <row> element in the XML, with CSV columns mapped as attributes.
*/
@XmlRootElement(name = "row") // This annotation is technically not needed here if it's an @XmlElement within Root
@XmlAccessorType(XmlAccessType.FIELD) // JAXB will access fields directly
public class RowData {
@XmlAttribute(name = "col1")
private String col1;
@XmlAttribute(name = "col2")
private String col2; // Use String for flexibility, convert as needed
@XmlAttribute(name = "col3")
private String col3;
@XmlAttribute(name = "col4")
private String col4;
@XmlAttribute(name = "col5")
private String col5;
// Default constructor for JAXB
public RowData() {}
// Constructor to easily create RowData objects from parsed CSV data
public RowData(String col1, String col2, String col3, String col4, String col5) {
this.col1 = col1;
this.col2 = col2;
this.col3 = col3;
this.col4 = col4;
this.col5 = col5;
}
// Getters and Setters (optional if using XmlAccessType.FIELD, but good practice)
public String getCol1() { return col1; }
public void setCol1(String col1) { this.col1 = col1; }
public String getCol2() { return col2; }
public void setCol2(String col2) { this.col2 = col2; }
public String getCol3() { return col3; }
public void setCol3(String col3) { this.col3 = col3; }
public String getCol4() { return col4; }
public void setCol4(String col4) { this.col4 = col4; }
public String getCol5() { return col5; }
public void setCol5(String col5) { this.col5 = col5; }
}注解说明:
接下来,我们需要编写代码来读取CSV文件,解析每一行数据,并将其转换为RowData对象,最终将这些对象添加到Root实例中。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
public class CsvParser {
/**
* Parses a CSV file and populates a Root object with RowData instances.
* Assumes the first line is a header and skips it.
*
* @param csvFilePath The path to the CSV file.
* @param delimiter The delimiter used in the CSV file (e.g., ",").
* @return A Root object containing parsed CSV data.
* @throws IOException If an I/O error occurs during file reading.
*/
public static Root parseCsv(String csvFilePath, String delimiter) throws IOException {
Root root = new Root();
try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
String line;
// Read and skip the header line
br.readLine();
while ((line = br.readLine()) != null) {
// Handle potential empty lines
if (line.trim().isEmpty()) {
continue;
}
String[] fields = line.split(delimiter, -1); // -1 to keep trailing empty strings
// Ensure we have enough fields, pad with empty strings if necessary
String[] paddedFields = Arrays.copyOf(fields, 5);
for (int i = 0; i < paddedFields.length; i++) {
if (paddedFields[i] == null) {
paddedFields[i] = ""; // Replace null with empty string
}
}
try {
// Create a RowData object from the parsed fields
RowData rowData = new RowData(
paddedFields[0],
paddedFields[1],
paddedFields[2],
paddedFields[3],
paddedFields[4]
);
root.addRow(rowData);
} catch (Exception e) {
System.err.println("Error processing CSV line: " + line + ". Skipping. Error: " + e.getMessage());
}
}
}
return root;
}
}代码说明:
最后一步是使用JAXB的Marshaller将填充好的Root对象转换为XML文件。
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class XmlGenerator {
/**
* Generates an XML file from a Root object using JAXB Marshaller.
*
* @param rootObject The Root object containing the data.
* @param xmlFilePath The desired path for the output XML file.
*/
public static void generateXml(Root rootObject, String xmlFilePath) {
try {
// Create JAXBContext for the Root and RowData classes
JAXBContext jaxbContext = JAXBContext.newInstance(Root.class, RowData.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// Set property to format the output XML nicely
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Output XML to console for quick verification
System.out.println("--- Generated XML (Console Output) ---");
jaxbMarshaller.marshal(rootObject, System.out);以上就是Java中CSV数据转换为带属性的XML:JAXB实现教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号