本例使用的xml解析方式为jdom
...
<ROOT>
<Consignment>
...
</Consignment>
</ROOT>
解析xml文件
InputStream xmlFileStream = new FileInputStream(xmlFile);
SAXBuilder builder = new SAXBuilder(new XMLReaderSAX2Factory(false));
Document document = builder.build(xmlFileStream);
Element root = document.getRootElement();
获得Consignment元素
Element consignElement = root.getChild("Consignment");
遍历元素封装Bean
public static Consignment getConsignment(Element consignElement) throws Exception {
Consignment consignment = null; try {
List<Element> elements = consignElement.getChildren();
Class<?> consignmentClz = Class.forName("com.entity.po.consignment.Consignment");
consignment = (Consignment) consignmentClz.newInstance();
for(Element ele : elements){
CheckTypeUtil.checkType(consignment, consignmentClz, ele);
}
} catch (Exception e) {
throw e;
} return consignment;
}
/**
* 解析对象时过滤字段属性类型
* @param sampleDnaGene
* @param sampleDnaGeneClz
* @param element
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public static void checkType(Object object, Class<?> objectClz, Element chiledEle)
throws NoSuchFieldException, IllegalAccessException {
Field field = objectClz.getDeclaredField(chiledEle.getName());
field.setAccessible(true);
if("java.lang.Integer".equals(field.getType().getName())
|| "int".equals(field.getType().getName())){
if (!StringUtils.isEmpty(chiledEle.getTextTrim())) {
field.set(object,Integer.parseInt(chiledEle.getTextTrim()));
}
}else if("java.lang.Long".equals(field.getType().getName())
|| "long".equals(field.getType().getName())){
if(!StringUtils.isEmpty(chiledEle.getTextTrim())){
field.set(object,Long.parseLong(chiledEle.getTextTrim()));
}
}else if("java.util.Date".equals(field.getType().getName())){
if (!StringUtils.isEmpty(chiledEle.getTextTrim())) {
field.set(object, DateTools.stringToDate(chiledEle.getTextTrim()));
}
}else if("java.lang.Double".equals(field.getType().getName())
|| "double".equals(field.getType().getName())){
if(!StringUtils.isEmpty(chiledEle.getTextTrim())){
field.set(object,Double.parseDouble(chiledEle.getTextTrim()));
}
}else if("java.lang.Float".equals(field.getType().getName())
|| "float".equals(field.getType().getName())){
if(!StringUtils.isEmpty(chiledEle.getTextTrim())){
field.set(object,Float.parseFloat(chiledEle.getTextTrim()));
}
}else if("java.lang.Short".equals(field.getType().getName())
|| "short".equals(field.getType().getName())){
if(!StringUtils.isEmpty(chiledEle.getTextTrim())){
field.set(object,Short.parseShort(chiledEle.getTextTrim()));
}
}else{
if (!StringUtils.isEmpty(chiledEle.getTextTrim())) {
field.set(object, chiledEle.getTextTrim());
}else{
field.set(object,null);
}
}
}