用dom解析xml文件

用dom解析xml文件

步骤如下:

1、创建dom的解析工厂     
2、创建解析xml的dom对象
3、获取文件的元素节点
4、遍历节点,取出元素


第一步:

1.建立一个xml文件


例如:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<infos>
 <city id="1">
 <temperature>20-30度</temperature>
 <wind>南风3-4级</wind>
 <weather>5月20日 多云转阴</weather>
 <name>上海</name>
 <pm>200</pm>
 </city>
 <city id="2">
 <temperature>26-30度</temperature>
 <wind>南风7-8级</wind>
 <weather>5月20日 多云转阴</weather>
 <name>北京</name>
 <pm>800</pm>
 </city>
 <city id="3">
 <temperature>28-33度</temperature>
 <wind>南风5-6级</wind>
 <weather>5月20日 多云转阴</weather>
 <name>四川</name>
 <pm>400</pm>
 </city>
</infos>


第二步:

2.根据xml文件封装自己想要的类

例如:

public class WeatherInfo {


private int id;
private String temperature;
private String wind;
private String weather;
private String name;

private String pm;


public WeatherInfo() {


}


@Override
public String toString() {
return "WeahterInfo [id=" + id + ", temperature=" + temperature
+ ", wind=" + wind + ", weather=" + weather + ", name=" + name
+ ", pm=" + pm + "]";
}


public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}


public String getTemperature() {
return temperature;
}


public void setTemperature(String temperature) {
this.temperature = temperature;
}


public String getWind() {
return wind;
}


public void setWind(String wind) {
this.wind = wind;
}


public String getWeather() {
return weather;
}


public void setWeather(String weather) {
this.weather = weather;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public String getPm() {
return pm;
}


public void setPm(String pm) {
this.pm = pm;
}


}


第三步:

3.创建一个类,用于解析xml文件,及为:用dom解析xml文件

例如:

// 用dom解析xml文件
public static List<WeatherInfo> getListInfoForDom(InputStream inputStream)
throws Exception {
List<WeatherInfo> list = new ArrayList<WeatherInfo>();
// 创建dom的解析工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
// weatherinfo的里面的一个对象
Document document = documentBuilder.parse(inputStream);
// 获取文件元素的节点
Element element = document.getDocumentElement();


NodeList cityList = element.getElementsByTagName("city"); // 从一个对象的city开始遍历
// 循环该节点下的所有节点
for (int i = 0; i < cityList.getLength(); i++) {
Element elementCity = (Element) cityList.item(i);
WeatherInfo info = new WeatherInfo();
info.setId(Integer.parseInt(elementCity.getAttribute("id")));


// 获取city下的子节点元素
NodeList childForCityList = elementCity.getChildNodes();
for (int j = 0; j < childForCityList.getLength(); j++) {
if (childForCityList.item(j).getNodeType() == Node.ELEMENT_NODE) {
if ("temperature".equals(childForCityList.item(j)
.getNodeName())) {
info.setTemperature(childForCityList.item(j)
.getFirstChild().getNodeValue());
} else if ("wind".equals(childForCityList.item(j)
.getNodeName())) {
info.setWind(childForCityList.item(j).getFirstChild()
.getNodeValue());
} else if ("weather".equals(childForCityList.item(j)
.getNodeName())) {
info.setWeather(childForCityList.item(j)
.getFirstChild().getNodeValue());
} else if ("name".equals(childForCityList.item(j)
.getNodeName())) {
info.setName(childForCityList.item(j).getFirstChild()
.getNodeValue());
} else if ("pm".equals(childForCityList.item(j)
.getNodeName())) {
info.setPm(childForCityList.item(j).getFirstChild()
.getNodeValue());
}
}
}


list.add(info);
}
return list;
}


第四步:

4.在android中调用即可

例如:

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.tv_msg);


try {
// 加载本地xml文件
List<WeatherInfo> list = WeatherService
.getListInfoForDom(MainActivity.class.getClassLoader()
.getResourceAsStream("weather.xml"));


StringBuffer sb = new StringBuffer();
for (WeatherInfo info : list) {
String str = info.toString();
sb.append(str);
sb.append("\n\n");
}
textView.setText(sb.toString() + "");
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(this, "解析失败", Toast.LENGTH_LONG).show();
}
}

}


注释:以上代码复制即可使用,

    代码中都标有很清晰的注释,以便于各位进行理解

    但是介意自己动手写,小编也是新手

            有问题可留言。



你可能感兴趣的:(xml,android,dom,StringBuffer)