dom方法解析xml文件

xml文件放在sdcard中,dom方式解析,然後在textView上展示(針對於標準格式的xml)

TextView textView=(TextView) findViewById(R.id.textView);
List<Person> listPerson=new ArrayList<Person>();

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//sdcard路徑
String sdcardPath=Environment.getExternalStorageDirectory().getPath();
//找到文件
File personsFile=new File(sdcardPath+"/persons.xml");

if(personsFile.exists()){//文件存在就解析
try {
//得到文件建造工廠
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//得到建造器
DocumentBuilder builder = factory.newDocumentBuilder();

try {
//加載personsFile.xml文件爲document文檔,來解析
Document document = builder.parse(personsFile);
//得到根節點persons
Element root = document.getDocumentElement();
//得到根節點的所有子節點,也就是兩個person和三個空格
NodeList nodes = root.getChildNodes();
//遍歷集合,獲得每一個子節點
for(int i=0;i<nodes.getLength();i++){
//得到一個節點
Node n = nodes.item(i);
//判斷當前節點是不是元素節點
if(n.getNodeType()==Node.ELEMENT_NODE){
Person p=new Person();//創建person對象,收集數據
Element ele=(Element) n;//某一個person節點
String id=ele.getAttribute("id");//person節點的id屬性值
p.setId(Integer.parseInt(id));//封裝id

//得到當前person的子節點name和age
NodeList colums = ele.getChildNodes();
for(int j=0;j<colums.getLength();j++){
//得到子節點name或age
Node item = colums.item(j);
//判斷當前節點是不是元素節點
if(item.getNodeType()==Node.ELEMENT_NODE){
Element element=(Element) item;
//取出文本節點的值
String value=element.getFirstChild().getNodeValue();
if(element.getNodeName().equals("name")){
p.setName(value);
}else if(element.getNodeName().equals("age")){
p.setAge(Integer.parseInt(value));
}
}
}
//一個person處理完,就可以保存person對象了
listPerson.add(p);
}

}
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
Toast.makeText(MainActivity.this, "sdcard不存在", 0).show();
}
textView.setText(listPerson.toString());


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章