我是Spring和Spring Batch的新手,并决定使用它将一堆xml文件导出到需要我们数据库中的xml文件的第三方。我的问题是,我使用StaxEventItemWriter将对象转换为xml,但我得到如下输出:
<categories><category>First Aid / Safety / Medical</category></categories>
我想要的时候
<categories><category>First Aid / Safety / Medical</category></categories>
我的作家被定义为:
@Bean(name="OG-ProductWriter")
ItemWriter<ProductXml> productWriter() {
StaxEventItemWriter<ProductXml> writer = new StaxEventItemWriter<>();
writer.setResource(new FileSystemResource(exportDir + "\\product-feed.xml"));
writer.setRootTagName("products");
// they require ascii
writer.setEncoding("ASCII");
writer.setMarshaller(getMarshaller());
return writer;
}
Marshaller as:
@Bean(name="OG-Unmarshaller")
public Marshaller getMarshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
Map<String, Object> props = new HashMap<>();
//these do nothing
props.put("jaxb.formatted.output", true);
props.put("com.sun.xml.bind.marshaller.CharacterEscapeHandler", new XmlCharacterHandler());
marshaller.setClassesToBeBound(ProductXml.class);
//this causes exception
//marshaller.setJaxbContextProperties(props);
marshaller.setMarshallerProperties(props);
return marshaller;
}
我被要求提供有关配置的更多信息。我没有使用XML配置并通过java配置完成所有操作。阅读器只是一个JPA存储库阅读器,处理器获取JPA对象并将其复制到productXml产品对象。我可以包含更多,但我不确定还有什么与我提出的问题相关。 该步骤定义为
@Bean(name="OG-ProductExportStep")
Step ogProductExport() {
return stepBuilderFactory.get("ogProductFeed")
.<Product,ProductXml>chunk(500)
.reader(productReader())
.processor(productProcessor())
.writer(productWriter())
.build();
}
我尝试过使用CastorMarshaller,XStreamMarshaller,但我可能只是没有传递正确的参数。我一直在拉着我的头发试图让它工作,搜索高低,只是没有找到任何解决方案。任何建议都将不胜感激。
这是一个我发现我尝试添加为属性的类,但它没有做任何事情:
public class XmlCharacterHandler implements CharacterEscapeHandler {
public void escape(char[] buf, int start, int len, boolean isAttValue,
Writer out) throws IOException {
StringWriter buffer = new StringWriter();
for (int i = start; i < start + len; i++) {
buffer.write(buf[i]);
}
String st = buffer.toString();
if (!st.contains("CDATA")) {
st = buffer.toString().replace("&", "&").replace("<", "<")
.replace(">", ">").replace("'", "'")
.replace("\"", """);
}
out.write(st);
System.out.println(st);
}
}`
我的对象如果有帮助:
@XmlRootElement(name = "product")
@XmlAccessorType(XmlAccessType.FIELD)
public @Data class ProductXml {
@XmlElement(name = "product_id")
private int product_id;
//this gives the same escaping problem
@XmlElement(name = "name")
private String name;
@XmlElement(name = "sku")
private String sku;
// cheated and just made string categories.add("<category>string</category>").
// The < and > get translated to < and >
@XmlElement(name = "categories")
private ArrayList<String> categories
....(the rest defined the same)
}