在数据处理场景中,将csv格式的表格数据转换为xml格式是一种常见的需求。然而,有时我们需要的xml结构并非将csv的每一列转换为独立的子元素,而是作为父元素的属性(attribute)。例如,我们可能希望将以下csv数据:
Col1,Col2,Col3,Col4,Col5 All,0,,0,0 All,935,231,0,30 None,1011,257,0,30
转换为如下带有属性的XML格式:
直接使用Java的DOM API(如DocumentBuilder和Transformer)进行转换时,通常会生成以列名作为标签的子元素,而非属性。这正是本文要解决的核心问题。
在上述问题背景中提到的传统DOM方式,其核心逻辑是通过遍历CSV的每一行和每一列,为每个数据点创建一个新的Element。例如,newDoc.createElement(csvFields[i++])会根据CSV头部的列名创建
|
All 0 0 0
显然,这种方式生成的是元素(Element),而不是我们期望的属性(Attribute)。要实现属性形式的转换,我们需要一种更灵活的XML绑定机制。
JAXB(Java Architecture for XML Binding)是Java平台上的一个标准API,用于将Java对象与XML文档进行相互转换(即编组/Marshalling和解组/Unmarshalling)。通过使用JAXB提供的注解,我们可以精确控制Java对象如何映射到XML结构,包括将字段映射为XML属性。
要将CSV的每一行转换为一个带有属性的
首先,我们需要一个根元素来包含所有的
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
import java.util.ArrayList;
// 根元素包装类
@XmlRootElement(name = "root")
public class RootElement {
private List rows = new ArrayList<>();
@XmlElement(name = "row")
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
public void addRow(Row row) {
this.rows.add(row);
}
}
接下来,定义表示CSV每一行的POJO类,并使用@XmlAttribute注解:
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;
// 表示CSV每一行的POJO
@XmlRootElement(name = "row") // 可选,但为了清晰性可以加上
@XmlAccessorType(XmlAccessType.FIELD) // 指定JAXB访问字段
public class Row {
@XmlAttribute(name = "col1")
private String col1;
@XmlAttribute(name = "Col2") // 注意:XML属性名是大小写敏感的
private String col2;
@XmlAttribute(name = "Col3")
private String col3;
@XmlAttribute(name = "Col4")
private String col4;
@XmlAttribute(name = "Col5")
private String col5;
// 无参构造函数是JAXB的要求
public Row() {}
public Row(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;
}
// Getter和Setter方法 (JAXB在XmlAccessType.FIELD时不需要,但良好实践建议保留)
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文件读取、解析,并将数据填充到Row对象列表中,最后使用JAXB将这些对象编组为XML。
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class CsvToXmlConverter {
public static void convertCsvToXmlWithAttributes(String csvFileName, String xmlFileName, String delimiter) {
RootElement root = new RootElement();
List header = new ArrayList<>();
try (BufferedReader csvReader = new BufferedReader(new FileReader(csvFileName))) {
String line;
boolean isHeader = true;
while ((line = csvReader.readLine()) != null) {
if (line.trim().isEmpty()) {
continue; // 跳过空行
}
String[] values = line.split(delimiter, -1); // -1参数确保保留末尾的空字符串
if (isHeader) {
// 假设第一行是CSV头,我们在这里不直接使用它来创建Row对象,
// 但在更复杂的场景中,可以用来动态映射列名
header.addAll(Arrays.asList(values));
isHeader = false;
} else {
// 创建并填充Row对象
// 这里假设CSV列的顺序与Row类的字段顺序一致
// 实际应用中可能需要更健壮的映射逻辑
if (values.length >= 5) { // 确保有足够的列
Row row = new Row(
values[0].trim(),
values[1].trim(),
values[2].trim(),
values[3].trim(),
values[4].trim()
);
root.addRow(row);
} else {
System.err.println("警告: CSV行数据列数不足,跳过此行: " + line);
}
}
}
// 使用JAXB进行编组
JAXBContext jaxbContext = JAXBContext.newInstance(RootElement.class, Row.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// 设置输出格式
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // 设置编码
// 将对象编组到文件
jaxbMarshaller.marshal(root, new File(xmlFileName));
System.out.println("CSV数据已成功转换为XML文件: " + xmlFileName);
} catch (IOException e) {
System.err.println("文件操作错误: " + e.getMessage());
} catch (Exception e) {
System.err.println("JAXB或数据处理错误: " + e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
// 创建一个示例CSV文件
String csvContent = "Col1,Col2,Col3,Col4,Col5\n" +
"All,0,,0,0\n" +
"All,935,231,0,30\n" +
"None,1011,257,0,30";
String csvFileName = "sample.csv";
try {
java.nio.file.Files.write(java.nio.file.Paths.get(csvFileName), csvContent.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
String xmlFileName = "output_with_attributes.xml";
String delimiter = ","; // CSV分隔符
convertCsvToXmlWithAttributes(csvFileName, xmlFileName, delimiter);
}
} 代码解析:
jakarta.xml.bind jakarta.xml.bind-api2.3.3 org.glassfish.jaxb jaxb-runtime2.3.3
通过本教程,我们学习了如何利用Java的JAXB框架,结合POJO类和@XmlAttribute等注解,将CSV数据高效准确地转换为带有属性的XML文件。相较于传统的DOM操作,JAXB提供了一种更声明式、更类型安全的方式来处理Java对象与XML之间的映射,大大简化了开发过程,并能生成符合特定结构要求的XML输出。掌握JAXB是Java开发中处理XML数据的重要技能之一。