赞
踩
//今天是新公司的第一天,说是要搞培训,写了个xml的解析程序。。。
- package com.kaitong.xml;
-
-
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
-
-
- import org.dom4j.Document;
- import org.dom4j.Element;
- import org.dom4j.io.SAXReader;
-
-
- public class MyXMLPrase {
- public static void main(String[] args) throws Exception{
- //首先定义一个List格式的数据
- String filePath="d:/kaitong.xml";
- List<Map<String,String>> list=saxReader(filePath);
- print(list);
-
- System.out.println("1.按照for循环删除 2.按照迭代删除");
- int chance=System.in.read()-48;
-
- if(1==chance){
- deleteByfor(list);
- }else if(2==chance){
- deleteByIterator(list);
- }else{
- System.out.println("您输入的参数有误...");
- return;
- }
-
- print(list);
- }
-
- //解析对应的xml文件
- public static List<Map<String,String>> saxReader(String filePath){
- File xmlFile = new File(filePath);
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(xmlFile);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- System.err.println("File is not exsit!");
- }
-
- SAXReader saxReader = new SAXReader();
- List rowList=null;
- List<Map<String, String>> resultList = new ArrayList<Map<String,String>>();
-
- try {
- //生成文档对应实体
- Document doc = saxReader.read(fis);
- //获取指定路径下的元素列表,这里指获取所有的data下的row元素
- rowList = doc.selectNodes("//xml-body/line");
-
- Iterator iterator=rowList.iterator();
-
- while(iterator.hasNext()){
- Map<String,String> nodeMap=new HashMap<String,String>();
- Element element = (Element)iterator.next();
-
- //获取line元素的所有属性列表
- List elementList = element.elements();
-
-
- Iterator child=elementList.iterator();
-
- while(child.hasNext()){
- //将每个属性转化为一个抽象属性,然后获取其名字和值
- Element aa=(Element) child.next();
- nodeMap.put(aa.getName(),element.elementText(aa.getName()));
- }
- resultList.add((HashMap<String, String>) nodeMap);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return resultList;
- }
-
- //打印对应的集合
- public static void print(List<Map<String,String>> list){
- int size=list.size();
- System.out.println("list集合的大小为:"+size);
-
- for(int i=0;i<size;i++){
- Map<String,String> map=list.get(i);
- for (String key : map.keySet()) {
- System.out.println("key= "+ key + " and value= " + map.get(key));
- }
- System.out.println();
- }
- }
-
- //删除元素通过for循环
- public static void deleteByfor(List<Map<String,String>> list){
- int size=list.size();
- for(int i=0;i<size-1;i++){
- list.remove(0);
- }
- }
-
- //删除元素通过迭代方式
- public static void deleteByIterator(List<Map<String,String>> list){
- int size=list.size();
- int i=0;
- Iterator it=list.iterator();
- while(it.hasNext()){
- if(++ i == size){
- break;
- }else{
- it.next();
- it.remove();
- }
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。