解析XML

SAX解析XML

2017-08-04  本文已影响6人  萤火之森ss
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();
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读