DOM解析XML文件实例
XML文件:
response:
// step 2:获得具体的dom解析器 DocumentBuilder db = dbf.newDocumentBuilder(); //System.out.println("class name: " + db.getClass().getName()); // step3: 解析一个xml文档,获得Document对象(根结点) Document document = db.parse(new File(xmlFilePath)); NodeList nodeList=document.getElementsByTagName("n:GetWeather"); Element element=(Element)nodeList.item(0); result=element.getElementsByTagName("n:CityName").item(0).getFirstChild().getNodeValue(); } catch (Exception e) { // TODO: handle exception } return result; } }?
// step 2:获得具体的dom解析器 DocumentBuilder db = dbf.newDocumentBuilder(); //System.out.println("class name: " + db.getClass().getName()); // step3: 解析一个xml文档,获得Document对象(根结点) Document document = db.parse(new File(xmlFilePath)); NodeList nodeList=document.getElementsByTagName("m:GetWeatherResponse"); Element element=(Element)nodeList.item(0); tempurature=element.getElementsByTagName("m:Temperature").item(0).getFirstChild().getNodeValue(); weather=element.getElementsByTagName("m:Weather").item(0).getFirstChild().getNodeValue(); System.out.println(tempurature+" "+weather); } catch (Exception e) { // TODO: handle exception } return tempurature; } }?
?
主函数:
import com.wjy.marshal.GetCityName;import com.wjy.marshal.GetCityWeather;public class zhu { public static void main(String args[]){ GetCityWeather getCityWeather=new GetCityWeather(); getCityWeather.getCityWeather(); GetCityName getCityName=new GetCityName(); System.out.println(getCityName.getCityName()); }}
?