2013-08-15 java解析xml

java解析xml

//获取document对象

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();

       DocumentBuilder dbBuilder;

       Document doc = null;

       try {

           dbBuilder = dbFactory.newDocumentBuilder();

           doc = dbBuilder.parse(url);

       } catch (ParserConfigurationException e) {

           e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

       } catch (SAXException e) {

           e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

       } catch (IOException e) {

           e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.

       }

       NodeList weatherList = doc.getElementsByTagName("weather");

       Element weatherElement = (Element)weatherList.item(0);

//解析xml

       NodeList conditionList = weatherElement.getElementsByTagName("condition");//获取结点List

       Element conditionElement = (Element)conditionList.item(0);//获取element

       String conditionYcode = conditionElement.getAttribute("ycode");//获取element属性


       Element forecastsElement = (Element)weatherElement.getElementsByTagName("forecasts").item(0);//获取element

       NodeList forecastsList = forecastsElement.getElementsByTagName("foreca");//获取element下NodeList

       int sizeForecasts = forecastsList.getLength();

       for (int i = 0; i < sizeForecasts; i++){//遍历NodeList

           Element forecaElement = (Element)forecastsList.item(i);//获取element

           String date = forecaElement.getAttribute("date");//获取element属性                            String strName=forecaElement.getFirstChild().getNodeValue();//获取element下变量值

       }


你可能感兴趣的:(java,document,null,change)