xml 프로필 읽 기

2318 단어 xml 읽 기

/**
 * 
 * @author chega
 * SAX  xml     ,
 *extends DefaultHandler
 *    startElement endElement Character         
 *    xml  node          HashMap ,        node   ,      Attribute
 */
public class MyXMLParser extends DefaultHandler{
	private static SAXParser parser;
	static{
		try {
			parser = SAXParserFactory.newInstance().newSAXParser();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}
	private static HashMap params ;
	private StringBuilder prefix ;
	public static HashMap parse(String filePath){
		try {
			parser.parse(filePath, new MyXMLParser());
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return params;
	}
	public static void main(String...args){
		System.out.println(parse("conf/XXX.xml"));
	}
	@Override
	public void startDocument ()throws SAXException{
		this.params = new HashMap();
		this.prefix = new StringBuilder();
	}
	@Override
	public void endDocument(){
		this.parser = null;
		this.prefix = null;
	}
	@Override
	public void startElement (String uri, String localName,String qName, Attributes attributes){
		if(this.prefix.length()>0){
			this.prefix.append("."+qName);
		}else{
			this.prefix.append(qName);
		}
	}
	@Override
	public void endElement (String uri, String localName, String qName)throws SAXException{
		if(this.prefix.lastIndexOf(".")!=-1){
			this.prefix.delete(this.prefix.lastIndexOf("."), this.prefix.length());
		}else{
			this.prefix.delete(0, this.prefix.length());
		}
	}
	@Override
	public void characters (char ch[], int start, int length)
			throws SAXException{
		String content = new String(ch,start,length).trim();
		if("".equals(content)){
			return ;
		}
		this.params.put(this.prefix.toString(), content);
	}
}


이것 은 Properties 파일 과 마찬가지 로 중복 되 는 설정 이 있 을 수 없습니다.

좋은 웹페이지 즐겨찾기