AndroidStudio使用XmlPullParser解析xml文件

1、问题描述

学习Android移动开发的时候,需要用到解析xml文件的部分,使用XmlPulParser类进行解析。

2、结果展示

xml文件为:
在这里插入图片描述

解析结果为:
在这里插入图片描述

3、代码实现

这里粘贴的核心代码,剩下的布局都是简单操作。

    private String parseXml() throws XmlPullParserException {
    
    
		
		//获取在xml目录下的people.xml文件
        XmlPullParser xrp = this.getResources().getXml(R.xml.people);

        String output="";
        String name = "",from = "",age = "";
        try{
    
    
        	//当xrp指针没有直到xml的最后一行
            while(xrp.next() != XmlPullParser.END_DOCUMENT){
    
    
                String people = xrp.getName();	//获取xml中的<people></people>数据
                								//因为本例中的xml文件只有一项数据
                if((people!=null) && (people.equals("person"))){
    
    
                    int count = xrp.getAttributeCount();	//获取xml文件中第一行数据
                    for (int i = 0; i < count; i++){
    
    
                        String attrName = xrp.getAttributeName(i);	//获取第i项数据的key
                        String attrValue = xrp.getAttributeValue(i);//获取第i项数据的value
                        if((attrName!=null) && attrName.equals("name")){
    
    
                            name = attrValue;
                        }else if((attrName!=null) && attrName.equals("from")){
    
    
                            from = attrValue;
                        }else if((attrName != null) && attrName.equals("age")){
    
    
                            age = attrValue;
                        }
                    }
                    if(count == 3 && (name!= null) && (from != null) && (age != null))
                        output +=  "姓名: "+name+", "+"来自: "+from+", "+"年龄: "+age+"\n";
                        //将结果都以一定的格式保存到outut中
                }
            }

        } catch (IOException e) {
    
    
            e.printStackTrace();
        }

        Toast.makeText(MainActivity.this,"output为:\n"+output,Toast.LENGTH_SHORT).show();
        return output;
    }

猜你喜欢

转载自blog.csdn.net/xdg15294969271/article/details/121410947