如何在Spring Batch中使用StaxEventItemReader解析XML?

时间:2019-10-30 14:33:50

标签: xml spring xml-parsing spring-batch stax

我得到一个巨大的XML文件作为批处理作业的输入。我正在尝试使用StaxEventItemReader,因为这不会将整个XML加载到内存中。我尝试了多种方法,但是XML没有被解析为Java对象。将XML分块转换为Java对象的最佳方法是什么?

XML

<?xml version="1.0" encoding="UTF-8"?>
<users>
 <user>
  <attribute name = "userName" rowAction = "ADD" >Jack</attribute>
  <attribute name = "age" rowAction = "DEL">22</attribute>
  <attribute name = "phoneNumber" rowAction = "ADD">111-222-3333</attribute>
 </user>
 <user>
  <attribute name = "userName" rowAction = "DEL" >Ram</attribute>
  <attribute name = "age" rowAction = "DEL">24</attribute>
  <attribute name = "phoneNumber" rowAction = "ADD">111-222-4444</attribute>
 </user>
</users>

物品阅读器

    @Bean
public StaxEventItemReader<User> userReader() {
    StaxEventItemReader<User> reader = new StaxEventItemReader<User>();
    reader.setResource(new FileSystemResource(feedFilePath));
    reader.setFragmentRootElementName("user");
    Map<String, Class<?>> aliases = new HashMap<>();
    aliases.put("user", User.class);
    reader.setUnmarshaller(xStreamMarshaller);
    return reader;
    }

用户类别

import java.util.List;

import javax.xml.bind.annotation.XmlRootElement;

import lombok.ToString;

@XmlRootElement(name = "user")
@ToString
public class User {
    private List<Attribute> attributes;
}
    /**
 * @return the attributes
 */
public List<Attribute> getAttributes() {
    return attributes;
}

/**
 * @param attributes the attributes to set
 */
public void setAttributes(List<Attribute> attributes) {
    this.attributes = attributes;
}
}

属性类

import javax.xml.bind.annotation.XmlAttribute;

public class Attribute {
private UserName userName;
private Age age;
private PhoneNumber phoneNumber;
/**
 * @return the userName
 */
public UserName getUserName() {
    return userName;
}
/**
 * @param userName the userName to set
 */
public void setUserName(UserName userName) {
    this.userName = userName;
}
/**
 * @return the age
 */
public Age getAge() {
    return age;
}
/**
 * @param age the age to set
 */
public void setAge(Age age) {
    this.age = age;
}
/**
 * @return the phoneNumber
 */
public PhoneNumber getPhoneNumber() {
    return phoneNumber;
}
/**
 * @param phoneNumber the phoneNumber to set
 */
public void setPhoneNumber(PhoneNumber phoneNumber) {
    this.phoneNumber = phoneNumber;
}

}

UserName类

import javax.xml.bind.annotation.XmlAttribute;

public class UserName {

private String value;
private String rowAction;

/**
 * @return the value
 */
@XmlAttribute(name = "userName")
public String getValue() {
    return value;
}

/**
 * @param value the value to set
 */
public void setValue(String value) {
    this.value = value;
}

/**
 * @return the rowAction
 */
@XmlAttribute(name = "rowAction")
public String getRowAction() {
    return rowAction;
}

/**
 * @param rowAction the rowAction to set
 */
public void setRowAction(String rowAction) {
    this.rowAction = rowAction;
}

}

0 个答案:

没有答案