
在数据处理场景中,我们有时会遇到一种特殊的XML文件格式,其核心业务数据并非以独立的XML元素结构化,而是以固定长度的扁平文本形式嵌入在某个XML元素的值中。例如,给定如下XML结构:
<?xml version="1.0" encoding="UTF-8"?> <File fileId="123" xmlns="abc:XYZ" > ABC123411/10/20 XBC128911/10/20 BCD456711/23/22 </File>
我们期望将<File>元素内部的文本内容(ABC123411/10/20等)解析成一系列结构化的Content对象,每个对象代表一行数据,包含name、id和date字段。例如:
name: ABC id: 1234 Date: 11/10/20
对应的Java模型可能定义如下:
public class Content {
private String name;
private String id;
private String date;
// 构造函数、Getter和Setter方法
public Content() {}
public Content(String name, String id, String date) {
this.name = name;
this.id = id;
this.date = date;
}
// Getters
public String getName() { return name; }
public String getId() { return id; }
public String getDate() { return date; }
// Setters
public void setName(String name) { this.name = name; }
public void setId(String id) { this.id = id; }
public void setDate(String date) { this.date = date; }
@Override
public String toString() {
return "Content{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", date='" + date + '\'' +
'}';
}
}直接使用Spring Batch的StaxEventItemReader配合JAXB进行解析时,通常会将<File>元素内部的所有文本内容作为一个整体字符串映射到POJO的@XmlValue字段。例如,如果定义一个TestRecord类:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "File", namespace = "abc:XYZ") // 注意:namespace需要与XML文件中的xmlns匹配
public class TestRecord {
@XmlValue
private String data;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}通过StaxEventItemReader读取后,TestRecord.data字段将包含整个多行字符串:
ABC123411/10/20 XBC128911/10/20 BCD456711/23/22
这种方法虽然成功读取了XML内容,但后续仍需手动编写代码来进一步解析这个长字符串,将其按行分割并按固定长度解析每个字段,这增加了额外的开发复杂性。
为了更优雅、高效地处理此类问题,推荐采用一种两阶段处理模型:
这种策略的优势在于:
此阶段的目标是从XML文件中抽取包含固定长度数据的文本内容,并写入一个新的扁平文件。这可以通过一个自定义的Spring Batch Tasklet来实现。
XmlDataExtractionTasklet将负责读取XML文件,使用JAXB或其他XML解析库(如DOM或SAX)来获取<File>元素内的文本值,然后将这个多行字符串写入一个新的临时文件。
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class XmlDataExtractionTasklet implements Tasklet, InitializingBean {
private Resource inputXmlResource;
private String outputFlatFilePath; // 临时扁平文件的路径
public void setInputXmlResource(Resource inputXmlResource) {
this.inputXmlResource = inputXmlResource;
}
public void setOutputFlatFilePath(String outputFlatFilePath) {
this.outputFlatFilePath = outputFlatFilePath;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(inputXmlResource, "inputXmlResource must be set");
Assert.hasText(outputFlatFilePath, "outputFlatFilePath must be set");
}
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
File inputFile = inputXmlResource.getFile();
File outputFile = new File(outputFlatFilePath);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
JAXBContext jaxbContext = JAXBContext.newInstance(TestRecord.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
TestRecord testRecord = (TestRecord) jaxbUnmarshaller.unmarshal(inputFile);
String rawData = testRecord.getData();
// 将原始数据按行写入新的扁平文件
if (rawData != null && !rawData.isEmpty()) {
writer.write(rawData.trim()); // trim()去除可能的首尾空白
}
contribution.incrementWriteCount(1); // 标记处理了一个XML文件
} catch (Exception e) {
// 记录错误或抛出异常
throw new IOException("Error extracting data from XML file: " + inputFile.getAbsolutePath(), e);
}
// 将输出文件路径存储到ExecutionContext,以便后续步骤访问
chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext()
.put("extracted.flat.filePath", outputFlatFilePath);
return RepeatStatus.FINISHED;
}
}TestRecord类:如前所示,用于JAXB解析XML获取@XmlValue。
在Spring Batch作业配置中,将此Tasklet定义为一个步骤。
<bean id="xmlDataExtractionTasklet" class="com.example.batch.XmlDataExtractionTasklet">
<property name="inputXmlResource" value="file:#{jobParameters['input.xml.path']}" />
<property name="outputFlatFilePath" value="#{jobExecutionContext['temp.flat.file.path']}" />
</bean>
<job id="dataProcessingJob">
<step id="extractXmlDataStep">
<tasklet ref="xmlDataExtractionTasklet" />
</step>
<!-- 后续步骤将使用此Tasklet生成的扁平文件 -->
<step id="processFlatFileStep" next="cleanUpStep">
<chunk reader="flatFileItemReader" processor="contentProcessor" writer="contentWriter" commit-interval="10" />
</step>
<step id="cleanUpStep">
<tasklet ref="fileCleaningTasklet" />
</step>
</job>
<!-- 定义临时文件路径,例如在Job启动时传入或动态生成 -->
<bean id="jobParameters" class="org.springframework.batch.core.configuration.support.MapJobParametersExtractor">
<property name="keys">
<map>
<entry key="input.xml.path" value="file:/path/to/your/input.xml"/>
<entry key="temp.flat.file.path" value="file:/path/to/temp/output.txt"/>
</map>
</property>
</bean>注意: temp.flat.file.path 可以通过jobExecutionContext在运行时动态生成,以确保唯一性。
此阶段的目标是利用FlatFileItemReader解析第一阶段生成的纯文本文件,并将其映射到Content对象。
Content类已在问题剖析部分给出,用于承载解析后的数据。
FlatFileItemReader需要配置一个LineTokenizer来解析每行数据。对于固定长度文件,我们使用FixedLengthTokenizer,并指定每个字段的起始和结束位置。然后,使用BeanWrapperFieldSetMapper将解析后的字段映射到Content对象的属性。
根据示例数据ABC123411/10/20,字段长度分析如下:
因此,字段范围是:
<bean id="flatFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
<property name="resource" value="file:#{jobExecutionContext['extracted.flat.filePath']}" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean class="org.springframework.batch.item.file.transform.FixedLengthTokenizer">
<property name="names" value="name,id,date" />
<property name="columns" value="1-3,4-7,8-15" />
</bean>
</property>
<property name="fieldSetMapper">
<bean class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
<property name="targetType" value="com.example.batch.Content" />
</bean>
</property>
</bean>
</property>
</bean>注意:resource属性通过#{jobExecutionContext['extracted.flat.filePath']}引用了第一阶段Tasklet写入ExecutionContext的临时文件路径,确保了数据流的连贯性。
将上述两个阶段整合到一个Spring Batch作业中,可以定义一个包含多个步骤的作业流。
<job id="fixedLengthXmlProcessingJob">
<!-- 步骤1: 提取XML中的扁平数据并写入临时文件 -->
<step id="extractDataFromXmlStep">
<tasklet ref="xmlDataExtractionTasklet" />
<next on="*" to="readAndProcessFlatFileStep"/>
</step>
<!-- 步骤2: 读取临时扁平文件并处理 -->
<step id="readAndProcessFlatFileStep">
<chunk reader="flatFileItemReader"
processor="contentItemProcessor" <!-- 可选:自定义数据处理逻辑 -->
writer="contentItemWriter" <!-- 实际数据写入逻辑 -->
commit-interval="100" />
<next on="*" to="cleanupTempFileStep"/>
</step>
<!-- 步骤3: 清理临时文件 (可选,但推荐) -->
<step id="cleanupTempFileStep">
<tasklet ref="fileCleaningTasklet" />
</step>
</job>
<!-- 定义一个简单的文件清理Tasklet -->
<bean id="fileCleaningTasklet" class="org.springframework.batch.core.step.tasklet.Tasklet">
<property name="filePath" value="#{jobExecutionContext['extracted.flat.filePath']}" />
</bean>
<!-- 示例文件清理Tasklet实现 -->
<bean id="fileCleaningTasklet" class="com.example.batch.FileCleaningTasklet">
<property name="filePath" value="#{jobExecutionContext['extracted.flat.filePath']}" />
</bean>// FileCleaningTasklet.java
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import java.io.File;
public class FileCleaningTasklet implements Tasklet, InitializingBean {
private String filePath;
public void setFilePath(String filePath) {
this.filePath = filePath;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.hasText(filePath, "filePath must be set");
}
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
File file = new File(filePath);
if (file.exists()) {
if (file.delete()) {
System.out.println("Cleaned up temporary file: " + filePath);
} else {
System.err.println("Failed to delete temporary file: " + filePath);
}
}
return RepeatStatus.FINISHED;
}
}注意事项:
通过将复杂问题分解为两个独立的、可管理的阶段,并充分利用Spring Batch提供的强大组件(如Tasklet和FlatFileItemReader),我们能够高效且优雅地解决从特殊XML结构中解析固定长度扁平数据的挑战。这种两阶段处理策略不仅提高了解决方案的清晰度和可维护性,也展现了Spring Batch在处理多样化数据源时的灵活性和强大能力。
以上就是Spring Batch解析嵌入式固定长度XML数据的两阶段策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号