18.3. 使用方法
要使用 BeanIODataFormat,您需要使用映射文件以及流的名称配置数据格式。
这可以按如下所示完成。streamName 是 employeeFile。
Java
XML
DataFormat format = new BeanIODataFormat(
"org/apache/camel/dataformat/beanio/mappings.xml",
"employeeFile");
// a route which uses the bean io data format to format the CSV data
// to java objects
from("direct:unmarshal")
.unmarshal(format)
// and then split the message body, so we get a message for each row
.split(body())
.to("mock:beanio-unmarshal");
// convert a list of java objects back to flat format
from("direct:marshal")
.marshal(format)
.to("mock:beanio-marshal");
<route>
<from uri="direct:unmarshal"/>
<unmarshal>
<beanio mapping="org/apache/camel/dataformat/beanio/mappings.xml" streamName="employeeFile"/>
</unmarshal>
<split>
<simple>${body}</simple>
<to uri="mock:beanio-unmarshal"/>
</split>
</route>
<route>
<from uri="direct:marshal"/>
<marshal>
<beanio mapping="org/apache/camel/dataformat/beanio/mappings.xml" streamName="employeeFile"/>
</marshal>
<to uri="mock:beanio-marshal"/>
</route>
要在 XML 中使用 BeanIO 数据格式,您需要使用 < beanio> XML 标签进行配置,如下所示。路由与上例类似。
第一个路由用于将 CSV 数据转换为 List<Employee> Java 对象。然后,我们分割,因此模拟端点会接收每行的消息。
第二个路由用于反向操作,将 List<Employee& gt; 转换为 CSV 数据流。
例如,CSV 数据可以如下:
Joe,Smith,Developer,75000,10012009
Jane,Doe,Architect,80000,01152008
Jon,Anderson,Manager,85000,03182007