SAX 解析XML文件

  SAX 解析XML文件,并将结果存放到map中:

实体类:

package buildXML;

import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * XML实体类
 * 该实体类可通过元素名称获得元素值
 * 或通过detail id获得detail对象
 * @author caij
 *
 */
public class XMLEntity implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = -698796041627370949L;
    //xml head标签下的内容
    public Map<String,String> head = new HashMap<String,String>();
    //xml body标签下的内容,生成xml是需要元素有顺序,所以采用LinkedHashMap
    public Map<String,Object> body = new LinkedHashMap<String, Object>();
    
    public XMLEntity(){
    }
    
    public XMLEntity(Map<String, String> head, Map<String, Object> body) {
        super();
        this.head = head;
        this.body = body;
    }

    public Map<String, String> getHead() {
        return head;
    }

    public void setHead(Map<String, String> head) {
        this.head = head;
    }

    public Map<String, Object> getBody() {
        return body;
    }

    public void setBody(Map<String, Object> body) {
        this.body = body;
    }
    
}

解析XML类,继承DefaultHandler

  1 package buildXML;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.util.HashMap;
  6 import java.util.Map;
  7 
  8 import javax.xml.parsers.ParserConfigurationException;
  9 import javax.xml.parsers.SAXParser;
 10 import javax.xml.parsers.SAXParserFactory;
 11 
 12 import org.xml.sax.Attributes;
 13 import org.xml.sax.SAXException;
 14 import org.xml.sax.helpers.DefaultHandler;
 15 
 16 /**
 17  * 
 18  *  类名: ParseXMLImpl.java
 19  *  功能:解析C端传入的xml文件
 20  *  
 21  *     修改:   
 22  *  
 23  *  @author caij  
 24  *    DateTime 2013-4-19 下午3:20:30
 25  */
 26 public class ParseXMLImpl extends DefaultHandler {
 27     private XMLEntity xmlEntity = new XMLEntity();//定义xml实体对象
 28     private Map<String, String> detailNode = new HashMap<String, String>();// 存放detail中的内容
 29     private String flag = "";//判断目前解析的是哪一部分
 30     private String key; //插入map的key值
 31     private String attribute; //detail 的 属性值
 32     
 33     /**
 34      * 获得sax解析器对象
 35      * @return
 36      */
 37     private static SAXParser getSAXParser(){
 38         SAXParserFactory factory = SAXParserFactory.newInstance();
 39         SAXParser parser = null;
 40         try {
 41             parser = factory.newSAXParser();
 42         } catch (ParserConfigurationException e) {
 43             e.printStackTrace();
 44         } catch (SAXException e) {
 45             e.printStackTrace();
 46         }
 47         return parser;
 48     }
 49 
 50     public XMLEntity parseAllXML(InputStream is) throws SAXException, IOException {
 51         SAXParser parser = getSAXParser();
 52         ParseXMLImpl parseXMLImpl = new ParseXMLImpl();
 53         parser.parse(is, parseXMLImpl);
 54         return xmlEntity;
 55     }
 56 
 57     public Map<String, String> parseXMLHead(InputStream is) throws SAXException, IOException {
 58         parseAllXML(is);
 59         return xmlEntity.head;
 60     }
 61 
 62     public Map<String, Object> parseXMLBody(InputStream is) throws SAXException, IOException {
 63         parseAllXML(is);
 64         return xmlEntity.body;
 65     }
 66 
 67     public String getValueByFieldNameInHead(InputStream is, String fieldName) throws SAXException, IOException {
 68         parseAllXML(is);
 69         Map<String,String> head = xmlEntity.head;
 70         String value = head.get(fieldName);
 71         return value;
 72     }
 73     
 74     @Override
 75     public void startDocument() throws SAXException {
 76         super.startDocument();
 77     }
 78 
 79     @Override
 80     public void endDocument() throws SAXException {
 81         super.endDocument();
 82     }
 83 
 84     @Override
 85     public void startPrefixMapping(String prefix, String uri)
 86             throws SAXException {
 87         super.startPrefixMapping(prefix, uri);
 88     }
 89 
 90     @Override
 91     public void startElement(String uri, String localName, String qName,
 92             Attributes attributes) throws SAXException {
 93         // 判断元素属于哪一部分
 94         if ("head".equals(qName)) {
 95             flag = "head";
 96         } else if ("body".equals(qName)) {
 97             flag = "body";
 98         } else if ("detail".equals(qName)) {
 99             flag = "detail" + attributes.getValue(0);
100         }
101         // 确定key值
102         if ("head".equals(flag) && !flag.equals(qName)) {// head的子节点,加入到head的map中
103             key = qName;
104         } else if ("body".equals(flag) && !flag.equals(qName)) {// body的子节点,加入body的map中
105             key = qName;
106         } else if (flag.startsWith("detail") && flag.startsWith(qName)) {// 如果element的名称为detail,则把该节点放入detailList中
107             attribute = attributes.getValue(0);
108         } else if (flag.startsWith("detail") && !flag.startsWith(qName)) {// detail的子节点,加入到detail的map中,map的key为detail的id属性
109             key = qName;
110         }
111         super.startElement(uri, localName, qName, attributes);
112     }
113 
114     @Override
115     public void endElement(String uri, String localName, String qName)
116             throws SAXException {
117         Map<String, String> d = new HashMap<String, String>();// 新建一个map对象便于存入body中
118         d = detailNode;
119         if (flag.startsWith("detail") && "detail".equals(qName)
120                 && detailNode.isEmpty() != true && attribute != null) {
121             xmlEntity.body.put(attribute.toString(), d);
122             detailNode = new HashMap<String, String>();
123             attribute = null;
124         }
125         super.endElement(uri, localName, qName);
126     }
127 
128     @Override
129     public void characters(char[] ch, int start, int length)
130             throws SAXException {
131         String s = new String(ch, start, length);
132 
133         if (!s.startsWith("\n")) {
134             if ("head".equals(flag)) {// head的子节点,加入到head的map中
135                 xmlEntity.head.put(key, s);
136                 key = null;
137             } else if ("body".equals(flag)) {// body的子节点,加入body的map中
138                 xmlEntity.body.put(key, s);
139                 key = null;
140             } else if (flag.startsWith("detail") && key != null) {// detail的子节点,加入到detail的map中,map的key为detail的id属性
141                 detailNode.put(key, s);
142                 key = null;
143             }
144         }
145         super.characters(ch, start, length);
146     }
147 
148 }

调用:

1 public static void main(String[] args) throws SAXException, IOException {
2         InputStream input = new BufferedInputStream(new FileInputStream(uri));
3 
4         parseAllXML(input);
5         System.out.println(xmlEntity.body.size());
6     }
原文地址:https://www.cnblogs.com/caijing/p/3036059.html