使用dom4j解析xml文件
根据需要,需要将中国境内的省市区描述的xml文件根据省市区分出两层,分别为省描述文件和市描述文件。
package xml;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4J {
public static Logger logger = Logger.getLogger(Dom4J.class);
public static void main(String[] args) throws Exception {
//读取省市关系描述文件
File file = new File("D:" + File.separator + "xml" + File.separator
+ "province_city.xml");
logger.info(file.length());
SAXReader reader = new SAXReader();
Document document = reader.read(file);
Element root = document.getRootElement();
Iterator iterator = root.elementIterator();
while (iterator.hasNext()) {
Element province = (Element) iterator.next();
logger.info(province.attributeValue("code") + ":"
+ province.attributeValue("value"));
File pfile = new File("D:" + File.separator + "xml"
+ file.separator + "file" + File.separator
+ "c"+province.attributeValue("code") + ".txt");
pfile.createNewFile();
//省描述文件输出流
FileOutputStream fos = new FileOutputStream(pfile);
StringBuffer sb = new StringBuffer("[");
Iterator cityIterator = province.elementIterator();
while (cityIterator.hasNext()) {
Element city = (Element) cityIterator.next();
logger.info(city.attributeValue("code") + ":"
+ city.attributeValue("value"));
sb.append("{"text":"" + city.attributeValue("value")
+ "",code:" + """ + city.attributeValue("code")
+ ""},");
File cfile = new File("D:" + File.separator + "xml"
+ file.separator + "file" + File.separator
+ city.attributeValue("code") + ".txt");
cfile.createNewFile();
Iterator contryIterator = city.elementIterator();
StringBuffer citySb = new StringBuffer("[");
while (contryIterator.hasNext()) {
Element contry = (Element) contryIterator.next();
citySb.append("{"text":""
+ contry.attributeValue("value") + "",code:"
+ """ + contry.attributeValue("code") + ""},");
logger.info(contry.attributeValue("code") + ":"
+ contry.attributeValue("value"));
}
//市描述文件输出流
FileOutputStream contryFos = new FileOutputStream(cfile);
contryFos
.write((citySb.substring(0, citySb.length() - 1) + "]")
.getBytes());
contryFos.close();
}
if (province.elements().size() > 0) {
fos.write((sb.substring(0, sb.length() - 1) + "]").getBytes());
fos.close();
}
}
}
}