package com.pengtao.www;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
publicclass ParseXMLUtil {
staticfinal String TARGET_NODE_NAME = "item";
staticfinalintTARGET_LEVEL = 3;
staticfinal String TARGET_COLUMN_NAME = "name";
public String outputPath = "output.xlsx";
public List<String> parseXML(String path) {
List<String> result = new ArrayList<String>();
try {
InputStream in = ParseXMLUtil.class.getResourceAsStream(path);
SAXReader reader = new SAXReader();
Document doc = reader.read(in); // get document object
Element rootElement = doc.getRootElement(); // "repository"
if(rootElement==null) {
thrownew Exception("Root node is blank");
}
List<Element> targetElements = new ArrayList<Element>();
targetElements.add(rootElement);
for(int i=0;i<TARGET_LEVEL;i++) {
targetElements = getChildNodes(targetElements);
}
for(Element itemNode : targetElements) {
if(itemNode.getName().equals(TARGET_NODE_NAME)){
String text = itemNode.getStringValue().trim();
String name = itemNode.attributeValue(TARGET_COLUMN_NAME);
if(text!=null && text.length()>=0) {
result.add(name);
result.add(text);
}
}
}
} catch (Exception e) {
System.err.println("Error:" + e);
e.printStackTrace();
}
return result;
}
@SuppressWarnings("unchecked")
private List<Element> getChildNodes(List<Element> eList) throws Exception {
List<Element> results = new ArrayList<Element>();
try {
if(eList != null && eList.size()>0) {
for(Element e : eList) {
results.addAll(e.elements());
}
}
} catch (Exception ex) {
thrownew Exception("Error in getChildNodes:" + ex);
}
return results;
}
publicstaticvoid main(String[] args) throws Exception {
String xmlName = "target.xml";
String outputPath = "result.xlsx";
if(args!=null && args.length>0) {
xmlName = args[0];
}
if(args!=null && args.length>1) {
outputPath = args[1];
}
ParseXMLUtil util = new ParseXMLUtil();
List<String> list = util.parseXML("/xml/"+xmlName);
if(!list.isEmpty()) {
System.out.println("XML "+xmlName+" "+list.size()+" Elements");
ExcelWriter wrt = new ExcelWriter();
wrt.buildXSLXExcel(list, "./output/"+outputPath);
System.out.println("Excel paresed success and outputpath is " + outputPath);
}
}
}