Новичок
Профиль
Группа: Участник
Сообщений: 12
Регистрация: 3.3.2009
Репутация: нет Всего: нет
|
Здраствуйте. Я решил написать парсер для файла вида: | Код | <?xml version="1.0" ?> <MMWEATHER> <REPORT type="frc3"> <TOWN index="27612" sname="%CC%EE%F1%EA%E2%E0" latitude="56" longitude="38"> <FORECAST day="10" month="3" year="2009" hour="9" tod="1" predict="18" weekday="3"> <PHENOMENA cloudiness="3" precipitation="6" rpower="0" spower="0"/> <PRESSURE max="737" min="735"/> <TEMPERATURE max="0" min="-2"/> <WIND min="2" max="5" direction="3"/> <RELWET max="99" min="94"/> <HEAT min="-5" max="-3"/> </FORECAST> <FORECAST day="10" month="3" year="2009" hour="15" tod="2" predict="24" weekday="3"> <PHENOMENA cloudiness="3" precipitation="6" rpower="0" spower="0"/> <PRESSURE max="736" min="734"/> <TEMPERATURE max="2" min="0"/> <WIND min="2" max="5" direction="3"/> <RELWET max="99" min="94"/> <HEAT min="-3" max="-1"/> </FORECAST> <FORECAST day="10" month="3" year="2009" hour="21" tod="3" predict="30" weekday="3"> <PHENOMENA cloudiness="3" precipitation="6" rpower="0" spower="0"/> <PRESSURE max="737" min="735"/> <TEMPERATURE max="1" min="-1"/> <WIND min="1" max="3" direction="4"/> <RELWET max="98" min="93"/> <HEAT min="-3" max="-1"/> </FORECAST> <FORECAST day="11" month="3" year="2009" hour="3" tod="0" predict="36" weekday="4"> <PHENOMENA cloudiness="3" precipitation="6" rpower="0" spower="0"/> <PRESSURE max="738" min="736"/> <TEMPERATURE max="0" min="-2"/> <WIND min="2" max="5" direction="6"/> <RELWET max="98" min="93"/> <HEAT min="-5" max="-3"/> </FORECAST> </TOWN> </REPORT> </MMWEATHER>
|
Вот код обработчика: | Код | import java.util.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import javax.xml.parsers.*;
class WeatherHandler extends DefaultHandler { private boolean parsingInProgress; private Vector myElement; private Forecast forecast; private Phenomena phenomena; private Pressure pressure; private Temperature temperature; private Wind wind; private Relwet relwet;
public void startElenment(String uri, String name, String qname, Attributes attrs){ //throws SAXException{ if(qname.equals("MMWEATHER")){} else if (qname.equals("REPORT")){} else if(qname.equals("TOWN")){} else if(qname.equals("FORECAST")) {forecast= new Forecast(attrs.getValue("day"), attrs.getValue("month"), attrs.getValue("year"),attrs.getValue("hour"), attrs.getValue("tod"),attrs.getValue("weekday"));} else if (qname.equals("PHENOMENA")){phenomena= new Phenomena(attrs.getValue("cloudiness"), attrs.getValue("precipitation")); forecast.setPhenomena(phenomena);} else if (qname.equals("PRESSURE")){pressure= new Pressure(attrs.getValue("max"), attrs.getValue("min"));forecast.setPressure(pressure);} else if (qname.equals("TEMPERATURE")){temperature= new Temperature(attrs.getValue("min"), attrs.getValue("max"));forecast.setTemperature(temperature);} else if (qname.equals("WIND")){wind= new Wind(attrs.getValue("min"), attrs.getValue("max"));forecast.setWind(wind);} else if (qname.equals("RELWET")){relwet= new Relwet(attrs.getValue("min"), attrs.getValue("max"));forecast.setRelwet(relwet);} else if(qname.equals("HEAT")){}
}*/ public void startElement(String uri, String name, String qname, Attributes attrs){
//throws SAXException{ if(qname.equals("MMWEATHER")){} else if (qname.equals("REPORT")){} else if(qname.equals("TOWN")){} else if(qname.equals("FORECAST")){ forecast= new Forecast(attrs.getValue("day"), attrs.getValue("FORECAST","month"), attrs.getValue("FORECAST","year"),attrs.getValue("FORECAST","hour"), attrs.getValue("FORECAST","tod"),attrs.getValue("weekday"));} else if (qname.equals("PHENOMENA")){ phenomena= new Phenomena(attrs.getValue(0), attrs.getValue(1)); forecast.setPhenomena(phenomena);} else if (qname.equals("PRESSURE")){ pressure= new Pressure(attrs.getValue(0), attrs.getValue(1)); forecast.setPressure(pressure);} else if (qname.equals("TEMPERATURE")){ temperature= new Temperature(attrs.getValue(0), attrs.getValue(1)); forecast.setTemperature(temperature); } else if (qname.equals("WIND")){ wind= new Wind(attrs.getValue(0), attrs.getValue(1)); forecast.setWind(wind);} else if (qname.equals("RELWET")){ relwet= new Relwet(attrs.getValue(0), attrs.getValue(1)); forecast.setRelwet(relwet);} else if(qname.equals("HEAT")){}}
public void startDocument(){ myElement=new Vector(); }
public void endDocument(){
}
public void endElement(String uri, String name, String qname){ //throws SAXException{ if(qname.equals("MMWEATHER")){} else if (qname.equals("REPORT")){} else if(qname.equals("TOWN")){} else if(qname.equals("FORECAST")){ addForecast(forecast); } else if(qname.equals("PHENOMENA")){
} else if(qname.equals("PRESSURE")){ } else if(qname.equals("TEMPERATURE")){ } else if(qname.equals("WIND")){ } else if(qname.equals("RELWET")){ } else if(qname.equals("HEAT")){} } public void addForecast(Forecast a){ myElement.addElement(a);} public int size(){return myElement.size();}
public Forecast getForecast(int k){ Forecast a =new Forecast(); a= (Forecast)myElement.elementAt(k); return a;} }
|
Я сделал пользовательские классы для тегов FORECAST,PHENOMENA, PRESSURE, TEMPERATURE, WIND,RELWET. Атрибуты REPORT, TOWN и HEAT мне не нужны. Вот пример | Код | public class Forecast { Forecast(){this.day=new String("we"); this.month=new String("we"); this.year=new String("we"); this.hour=new String("we"); this.tod=new String("we"); this.weekday=new String("we"); this.pheno=new Phenomena(); this.press=new Pressure(); this.relw=new Relwet(); this.temp=new Temperature(); this.wind1=new Wind();} Forecast(String a, String b, String c, String d, String e, String f){ this.day=a; this.month=b; this.year=c; this.hour=d; this.tod=e; this.weekday=f; this.pheno=new Phenomena(); this.press=new Pressure(); this.relw=new Relwet(); this.temp=new Temperature(); this.wind1=new Wind(); } private String day, month ,year, hour, tod, weekday; private Phenomena pheno; private Pressure press; private Relwet relw; private Temperature temp; private Wind wind1; public Phenomena getPhenomena(){return pheno;} public Pressure getPressure(){return press;} public Relwet getRelwet(){return relw;} public Temperature getTemperature(){return temp;} public Wind getWind(){return wind1;} public void setDay(String a){this.day=a;} public void setPhenomena(Phenomena a){this.pheno=a;} public void setPressure(Pressure a){this.press=a;} public void setRelwet(Relwet a){this.relw=a;} public void setTemperature(Temperature a){this.temp=a;} public void setWind(Wind a){this.wind1=a;} public void setMonth(String a){this.month=a;} public void setYear(String a){this.year=a;} public void setHour(String a){this.hour=a;} public void setTod(String atod){this.tod=atod;} public void setWeekday(String a){this.weekday=a;} public String getDay(){return day;} public String getMonth(){return month;} public String getYear(){return year;} public String getHour(){return hour;} public String getTod(){return tod;} public String getWeekday(){return weekday;} }
|
| Код | public class Phenomena { Phenomena(){this.cloudiness=new String("fd");this.precipitation=new String ("df");} Phenomena(String a, String b){ this.cloudiness=a; this.precipitation=b;
} private String cloudiness, precipitation; public void setCloudiness(String a){this.cloudiness=a;} public void setPrecipitation(String a){this.precipitation=a;} public String getCloudiness(){return cloudiness;} public String getPrecipitation(){return precipitation;} }
|
Классы PHENOMENA, PRESSURE, TEMPERATURE, WIND,RELWET построенны по одному принцыпу. У меня есть еще класс в котором хранится дополнительная инфа и масив обьектов класса FORECAST. | Код | public class CitiesInfo{ boolean isForm; int size; private Forecast forec[]; private String name; private String xml_file; public void setForecast(Forecast data,int i){this.forec[i]=data;} public Forecast getForec1(int i){return forec[i];} public boolean getIsForm(){return isForm;} public int getSize(){return size;} public void setSize(int i){this.size=i;} public void setIsForm(){this.isForm=true;} CitiesInfo(String a, Forecast b, Forecast c, Forecast d,Forecast e){ this.isForm=false; this.size=2; this.name=a; this.forec=new Forecast[4]; this.forec[0]=b; this.forec[1]=c; this.forec[2]=d; this.forec[3]=e; this.xml_file="nothing"; for(int i=0;i<4;i++) { this.forec[i]=new Forecast(); } }; CitiesInfo(String a, String b){ this.isForm=false; this.size=2; this.name=a; this.xml_file=b; this.forec=new Forecast[4]; for(int i=0;i<4;i++) { this.forec[i]=new Forecast(); } }; public String getName(){return name;} public String getFile(){return "http://informer.gismeteo.Ru/xmlinf/"+xml_file+".xml";} }
|
Теперь пришла пора и к мидлету | Код | import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import java.util.*; import javax.xml.parsers.*; import javax.microedition.midlet.*; import javax.microedition.io.*; import javax.microedition.lcdui.*; import org.xml.sax.Attributes; import javax.xml.parsers.SAXParserFactory;
public class mainMIDlet extends MIDlet implements CommandListener {
private List city; private Form form; private Command exit; private Command backCommand; public CitiesInfo Vinnytsya=new CitiesInfo("Vinnytsya","33562_1"); public CitiesInfo Donetsk=new CitiesInfo("Donetsk","34519_1"); public CitiesInfo Kyiv=new CitiesInfo("Kyiv","33345_1"); public CitiesInfo Dnepr=new CitiesInfo("Dnepropetrovsk","34504_1"); public CitiesInfo Zaporizzya=new CitiesInfo("Zaporizzya","34601_1"); public CitiesInfo Zutomur=new CitiesInfo("Zutomur","33325_1"); public CitiesInfo Lviv=new CitiesInfo("Lviv","33393_1"); public CitiesInfo Poltava=new CitiesInfo("Poltava","33506_1"); public CitiesInfo Chernigiv=new CitiesInfo("Chernigiv","33135_1"); private boolean midletPaused = false; public void startrApp(String url, CitiesInfo a) { if (midletPaused) { resumeMIDlet (); } else { initialize (); startMIDlet (); } midletPaused = false; try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); SAXParser saxParser = factory.newSAXParser(); HttpConnection fc = (HttpConnection)Connector.open(url); InputStream is = fc.openInputStream(); InputSource inputSource = new InputSource(is); WeatherHandler myEventHandler= new WeatherHandler(); saxParser.parse(inputSource, myEventHandler );/*[color=red]когда я после этой команды готел что вывести в форму действие не выполнялось, что-то тут не работает. После этой команды уже ничего не работает(([/color]*/ for (int i=0; i<myEventHandler.size(); i++) { a=new CitiesInfo(a.getName(),myEventHandler.getForecast(0),myEventHandler.getForecast(1),myEventHandler.getForecast(2),myEventHandler.getForecast(3)); //a.setForecast(myEventHandler.getForecast(i),i); a.setSize(myEventHandler.size()); // form.append((a.getForec1(i)).getDay()+"-"+(a.getForec1(i)).getMonth()+"-"+(a.getForec1(i)).getYear()+" "+(a.getForec1(i)).getHour()); } } catch(Exception ex) {} }
public void alert2(CitiesInfo a){ Forecast s =new Forecast(); s.setDay("hernya polychilas"); for (int i=0; i<a.getSize(); i++){ startrApp(a.getFile(), a); form.append((a.getForec1(i)).getDay()+"-"+(a.getForec1(i)).getMonth()+"-"+(a.getForec1(i)).getYear()+" "+(a.getForec1(i)).getHour()); form.append(((a.getForec1(i)).getTemperature()).getMin_temperature()+"..."+((a.getForec1(i)).getTemperature()).getMax_temperature()); form.append((a.getForec1(i)).getYear()); } form.append("1"); form.append("cfeas"); for(int i=0; i<a.getSize(); i++){form.append("1");} Display display = Display.getDisplay(this); display.setCurrent(form); switchDisplayable(null, form); }
private void initialize() { form = new Form("form");
}
public void startMIDlet() { switchDisplayable(null, getCity()); } public void resumeMIDlet() { }
public void switchDisplayable(Alert alert, Displayable nextDisplayable) { Display display = getDisplay(); if (alert == null) { display.setCurrent(nextDisplayable); } else { display.setCurrent(alert, nextDisplayable); } } public void commandAction(Command command, Displayable displayable) { if (displayable == city) { if (command == List.SELECT_COMMAND) { cityAction();//:|7-commandAction|2|16-postAction // write post-action user code here } else if (command == exit) { // write pre-action user code here exitMIDlet(); // write post-action user code here } } else if (displayable == form) { if (command == backCommand) { // write pre-action user code here switchDisplayable(null, getCity()); // write post-action user code here } else if (command == exit) { // write pre-action user code here exitMIDlet(); // write post-action user code here } } // write post-action user code here }
public List getCity() { if (city == null) { // write pre-init user code here city = new List("city", Choice.IMPLICIT); city.append("Vinnytsya", null); city.setSelectedFlags(new boolean[] { false}); public void cityAction() {{ String __selectedString = getCity().getString(getCity().getSelectedIndex()); if (__selectedString.equals("Vinnytsya")) {form=new Form("Vinnytsya"); startrApp(Vinnytsya.getFile(), Vinnytsya); form=new Form("Vinnytsya"); alert2(Vinnytsya); switchDisplayable(null, form); } } } public Form getForm(CitiesInfo a) { if (a.getIsForm()==false) { form = new Form("form", new Item[] { }); form.append("false"); }else{form = new Form("form"); form.append("true");}{ form.addCommand(getBackCommand()); form.addCommand(getExit()); form.setCommandListener(this); } return form; }
public Command getExit() { if (exit == null) {//GEN-END:|19-getter|0|19-preInit // write pre-init user code here exit = new Command("Exit", Command.EXIT, 0);//:|19-getter|1|19-postInit // write post-init user code here }//GEN-BEGIN:|19-getter|2| return exit; }
public Command getBackCommand() { if (backCommand == null) { // write pre-init user code here backCommand = new Command("Back", Command.BACK, 0); // write post-init user code here } return backCommand; } public Display getDisplay () { return Display.getDisplay(this); }
public void exitMIDlet() { switchDisplayable (null, null); destroyApp(true); notifyDestroyed(); }
public void startApp() { if (midletPaused) { resumeMIDlet (); } else { initialize (); startMIDlet (); } midletPaused = false; }
public void pauseApp() { midletPaused = true; }
public void destroyApp(boolean unconditional) { }
}
|
Спасибо.
|