SAX解析XML

作者: 萤火之森ss | 来源:发表于2017-08-04 18:30 被阅读6次
    package xml;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import java.util.LinkedList;
    import java.util.List;
    
    /**
     * Created by Wangjianxin on 2017/8/4 0004.
     */
    public class saxSql {
    
    
        public static void main(final String[] args) {
    
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            try {
                SAXParser parser = saxParserFactory.newSAXParser();
                parser.parse("D:\\car\\car-service\\src\\main\\resources\\com\\car\\service\\mapping\\ActivityCzMapper.xml",new DefaultHandler(){
                    private  int selectnum = 0;
                    private  String value = null;
                    private  List<String> sqlList = new LinkedList<String>();
                    @Override
                    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                        super.startElement(uri, localName, qName, attributes);
    
                        if(qName.equals("select")){
                            selectnum ++;
                           int len = attributes.getLength();
                           for(int i =0;i<len;i++){
    //                           System.out.println(attributes.getQName(i) + ": " + attributes.getValue(i));
                           }
                        }
                    }
                    @Override
                    public void endElement(String uri, String localName, String qName) throws SAXException {
                        super.endElement(uri, localName, qName);
                        if(qName.equals("select")){
                            System.out.println(value + "v");
                            sqlList.add(value);
                        }
                    }
    
                    @Override
                    public void characters(char[] ch, int start, int length) throws SAXException {
                        super.characters(ch, start, length);
                        String  s  = new String(ch,start,length).trim();
                        value = s;
                    }
    
                    @Override
                    public void endDocument() throws SAXException {
                        super.endDocument();
                        System.out.println(sqlList);
                    }
    
    
                });
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:SAX解析XML

        本文链接:https://www.haomeiwen.com/subject/mvdblxtx.html