创建Dom4j的Document用于解析xml
protected Element createDocument(String xml) {
try {
Document document = new SAXReader().read(Thread.currentThread()
.getContextClassLoader().getResourceAsStream(xml));
// Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
return root;
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
@Override
public void parseXML(String xml, List<AnnualTargetSummary> list) {
Element element = createDocument(xml);
// 提取统计月指标数据
List<Element> l = element.selectNodes("//deptTargetSummaries"); // 指标数据
if (null != l) {
for (int i = 0; i < l.size(); i++) {
Element __e = (Element) element.selectObject("//summarydate["
+ (i + 1) + "]");// 获取Summarydate节点
Element _e = l.get(i); // deptTargetSummaries
List<Element> infoList = _e
.selectNodes("targets/targetSummaries");
AnnualTargetSummary ats = new AnnualTargetSummary();
List<DeptmentSummary> dslist = new ArrayList<DeptmentSummary>();
ats.setDateStr(__e.getText()); // 设置月份
ats.setMonth(i + 1);
if (null != infoList) {
for (int j = 0; j < infoList.size(); j++) {
DeptmentSummary ds = new DeptmentSummary();
Element deptElement = (Element) _e
.selectObject("deptname[" + (j + 1) + "]");
ds.setDeptName(deptElement.getText());// 设置部门
Element summaries = infoList.get(j);
List<Element> summariesList = summaries
.selectNodes("name");
if (null != summariesList) {
List<SummaryInfo> summaryInfoList = new ArrayList<SummaryInfo>();
for (int k = 0; k < summariesList.size(); k++) {
SummaryInfo summaryInfo = new SummaryInfo();
Element value = summariesList.get(k);// 名称
summaryInfo.setName(value.getText());
value = (Element) summaries
.selectObject("unit[" + (k + 1) + "]");// 单位
summaryInfo.setUnit(value.getText());
value = (Element) summaries
.selectObject("completed[" + (k + 1)
+ "]");
summaryInfo.setCompleted(value.getText());
value = (Element) summaries
.selectObject("basiscompleted["
+ (k + 1) + "]");
summaryInfo.setBasiscompleted(value.getText());
value = (Element) summaries
.selectObject("yearcompleted["
+ (k + 1) + "]");
summaryInfo.setYearcompleted(value.getText());
summaryInfoList.add(summaryInfo);
}
ds.setSummaryInfoList(summaryInfoList);
}
dslist.add(ds);
}
ats.setDeptments(dslist);
}
list.add(ats);
}
}
}
解析
String xml = "GetAnnualTargetSummary.xml";
Parser parser = XMLParseFactory.getParser("GetAnnualTargetSummary");
List<AnnualTargetSummary> list = new ArrayList<AnnualTargetSummary>();
parser.parseXML(xml, list);