我正在编写一个批处理作业来解析XML,提取字段并将它们保存在数据库中。当解析XML时,它选取了2个根元素,但将所有字段保留为空,因此在我的数据库中有2个记录将为空字段。似乎弄不明白为什么它不能读取元素...提亚
@Bean
fun xmlFileItemReader(environment: Environment): ItemReader<ConsumerInfo> {
val xmlFileReader = StaxEventItemReader<ConsumerInfo>()
xmlFileReader.setResource(ClassPathResource(environment.getRequiredProperty(PROPERTY_XML_SOURCE_FILE_PATH)))
xmlFileReader.setFragmentRootElementName("ConsumerInfo")
val customerMarshaller = Jaxb2Marshaller()
customerMarshaller.setClassesToBeBound(ConsumerInfo::class.java)
xmlFileReader.setUnmarshaller(customerMarshaller)
return xmlFileReader
}Kotlin数据类
@XmlRootElement(name = "ConsumerInfo", namespace = *Its correct*)
@XmlAccessorType(XmlAccessType.FIELD)
data class ConsumerInfo(
@XmlElement(name = "LastName")
var lastName: String? = null,
@XmlElement(name = "FirstName")
var firstName: String? = null,
@XmlElement(name = "GenerationCode")
var generationCode: String? = null,
@XmlElement(name = "Street")
var street: String? = null,
@XmlElement(name = "City")
var city: String? = null,
@XmlElement(name = "State")
)XML
<ConsumerInfo>
<LastName>lastn</LastName>
<FirstName>firstn</FirstName>
<GenerationCode>g</GenerationCode>
<Street>strt</Street>
<City>cty</City>
<State>st</State>
</ConsumerInfo>
<ConsumerInfo>
<LastName>last</LastName>
<FirstName>first</FirstName>
<GenerationCode>gc</GenerationCode>
<Street>street</Street>
<City>city</City>
<State>state</State>
</ConsumerInfo> compile('org.springframework.boot:spring-boot-starter-batch')
compile('org.springframework.boot:spring-boot-starter-jdbc')
compile('com.fasterxml.jackson.module:jackson-module-kotlin')
// https://mvnrepository.com/artifact/org.springframework/spring-oxm
compile group: 'org.springframework', name: 'spring-oxm', version: '5.1.6.RELEASE'
compile("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
compile("org.jetbrains.kotlin:kotlin-reflect")
compile ('org.postgresql:postgresql')
testCompile('org.springframework.boot:spring-boot-starter-test')
}发布于 2019-05-07 04:12:49
更新:
在使用Kotlin数据类时,@XmlElement(name =“*”)似乎没有将读取器/编组程序映射到该字段,而是使用val名称尝试映射。如果你想在Kotlin中使用@XmlELement,你需要显式地创建你的getter。
Kotlin解决方案:
@XmlRootElement(name = "ConsumerInfo")
class DemoCustomer {
@get:XmlElement(name = "FirstName")
var firstName: String? = null
@get:XmlElement(name = "LastName")
var lastName: String? = null
}Java解决方案:
@XmlRootElement(name = "ConsumerInfo")
public class DemoCustomer {
private String firstName;
private String lastName;
@XmlElement(name= "FirstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@XmlElement(name = "LastName")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}https://stackoverflow.com/questions/55976829
复制相似问题