因此 CSV 数据格式将获取您的整个文件并将其作为地图返回。然后,您可以使用列名作为映射的键。
让我演示一下。我有一个名为 customerlist.csv 的小 csv 文件,如下所示:
name,surname
Michael,SMITH
James,JOHNSON
John,WILLIAMS
Robert,BROWN
David,JONES
William,MILLER
Mary,DAVIS
Christopher,GARCIA
Joseph,RODRIGUEZ
以下将读取 csv 文件将其转换为地图,然后将其逐行拆分,您可以直接引用列并读取它们的值。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring https://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext id="work-order-context" streamCache="true"
trace="false" xmlns="http://camel.apache.org/schema/spring"
messageHistory="true">
<dataFormats>
<csv id="csv" useMaps="true" ignoreEmptyLines="true"/>
</dataFormats>
<route id="readCsvRoute">
<from uri="file:src/main/resources/file?noop=true&delay=5000&idempotent=false&sendEmptyMessageWhenIdle=true"/>
<log message="this is the raw file: ${body}"/>
<unmarshal>
<custom ref="csv"/>
</unmarshal>
<log message="this is the csv format: ${body}"/>
<split parallelProcessing="false">
<simple>${body}</simple>
<log message="line ${headers.CamelSplitIndex} contains: ${body}"/>
<log message=" To get the name I can use the map with body.get(name) which equals: ${body.get(name)}" />
<log message=" To get the surname I can use the map with body.get(surname) which equals: ${body.get(surname)}" />
</split>
</route>
</camelContext>
</beans>
输出将是:
2020-08-13 14:07:46.025 INFO 44843 --- [/resources/file] readCsvRoute : line 0 contains: {name=Michael, surname=SMITH}
2020-08-13 14:07:46.051 INFO 44843 --- [/resources/file] readCsvRoute : To get the name I can use the map with body.get(name) which equals: Michael
2020-08-13 14:07:46.052 INFO 44843 --- [/resources/file] readCsvRoute : To get the surname I can use the map with body.get(surname) which equals: SMITH