通过SAX进行xml文件分析
1、实现自己的handler类,继承于DefaultHandler。后续作为SAXParser对象parse方法中的参数。主要功能是xml文件分析处理,遇到某一个节点,某一个节点结束,该节点的值等等。
public class SAXHandler extends DefaultHandler{ @Override public void startDocument() throws SAXException { log.debug("startDocument"); } @Override public void endDocument() throws SAXException { log.debug("endDocument"); if(parseFinished != null){ parseFinished.parseFinished(); } } @Override public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException { switch(qName){ case REQUEST_HEADER_S: break; case REQUEST_HEADER: TLV tlv = new TLV(); tlv.setTag(attributes.getValue(TAG)); tlv.setLength(attributes.getValue(LENGTH)); tlv.setValue(attributes.getValue(VALUE)); tlv.setOffset(attributes.getValue(OFFSET)); tlvList.add(tlv); log.debug("["+REQUEST_HEADER+"]"+tlv.toString()); break; case RESPONSE_HEADER_S: break; case RESPONSE_HEADER: TLV tlv1 = new TLV(); tlv1.setTag(attributes.getValue(TAG)); tlv1.setLength(attributes.getValue(LENGTH)); tlv1.setValue(attributes.getValue(VALUE)); tlv1.setOffset(attributes.getValue(OFFSET)); resTlvList.add(tlv1); log.debug("["+RESPONSE_HEADER+"]"+tlv1.toString()); break; } } @Override public void endElement(String uri,String qName) throws SAXException { super.endElement(uri,localName,qName); } @Override public void characters(char[] ch,int start,int length) throws SAXException { super.characters(ch,start,length); } }
saxParserFactory = SAXParserFactory.newInstance(); try{ saxParser = saxParserFactory.newSAXParser(); saxHandler = new SAXHandler(); }catch(SAXException e){ log.error(e.getMessage()); }catch(ParserConfigurationException e){ log.error(e.getMessage()); }
3、开始分析xml文件
public boolean parse(){ try{ saxParser.parse(new File(xmlFilePath),saxHandler); }catch(IOException e){ log.error(e.getMessage()); return false; }catch(SAXException e){ log.error(e.getMessage()); return false; } return true; }原文链接:https://www.f2er.com/xml/299294.html