xmllessonloader.java.svn-base

来自「一个JAVA程序员的游戏」· SVN-BASE 代码 · 共 78 行

SVN-BASE
78
字号
/*
 * XmlLessonLoader.java
 *
 * Created on 5. Dezember 2006, 21:02
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package kanjitori.lesson;

import com.sun.org.apache.xerces.internal.parsers.SAXParser;
import java.io.FileInputStream;
import java.io.FileReader;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import kanjitori.*;
import kanjitori.graphics.bot.Bot;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

/**
 *
 * @author Pirx
 */
public class XmlLessonLoader implements LessonLoader {
    
    public Lesson load(String id) {
        try {
            Lesson lesson = new Lesson();
            XMLReader xmlReader = new SAXParser();
            xmlReader.setContentHandler(new LessonHandler(lesson));
            InputSource is = new InputSource(new FileInputStream(id));
            xmlReader.parse(is);
            return lesson;
        } catch(Exception ex) {
            throw new IllegalArgumentException(ex);
        }
    }
    
    private static class LessonHandler extends DefaultHandler {
        
        private Lesson lesson;
        private Section section;
        
        LessonHandler(Lesson lesson) {
            this.lesson = lesson;
        }
        
        @Override
        @SuppressWarnings( "unchecked" )
        public void startElement(String uri, String localName, String qName, Attributes attributes){
            if ("section".equals(qName)) {
                String name = attributes.getValue("name");
                section = new Section(name);
            } else if("entry".equals(qName)) {
                String key = attributes.getValue("key");
                String values = attributes.getValue("value");
                String ordered = attributes.getValue("ordered");
                section.addEntry(new Entry(key, values.split("\\|"), ! "false".equalsIgnoreCase(ordered)));
            } else if ("lesson".equals(qName)) {
                lesson.setBotClass(attributes.getValue("bot"));
            }
        }
        
        @Override
        public void endElement(String uri, String localName, String qName) {
            if ("section".equals(qName)) {
                lesson.addSection(section);
                section = null;
            }
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?