Android XML解析器– XMLPullParser

本文介绍了使用XMLPullParser在Android应用中解析XML的教程。XMLPullParser是推荐的Android XML解析器,通过实例化和解析XML文件,从XML文档中提取相关信息。文章详细展示了如何创建XML文件、XMLPullParser的实例化方法以及解析过程。

Welcome to android xml parser example using XMLPullParser. We will have a sample XML file that we will parse in android app and display it on the page.

欢迎使用XMLPullParser的android xml解析器示例。 我们将有一个示例XML文件,该文件将在android应用程序中解析并显示在页面上。

Android XML解析器 (Android XML Parser)

XML stands for Extensible Mark-up Language. XML files are commonly parsed in android to retrieve the relevant information from them. There are three types of android XML parser that we can use.

XML代表可扩展标记语言 。 XML文件通常在android中进行解析,以从中检索相关信息。 我们可以使用三种类型的android XML解析器。

  1. SAX Parsers

    SAX解析器
  2. DOM Parsers

    DOM解析器
  3. XMLPullParser

    XMLPullParser

DOM Parser : DOM parser use an object based approach where the whole xml is loaded into the memory and validated. Then it starts parsing the xml document. It parses from the starting node to the end node. Particular nodes cannot be parsed. Overall it’s slower than the other two.

DOM解析器 :DOM解析器使用基于对象的方法,其中将整个xml加载到内存中并进行验证。 然后,它开始解析xml文档。 它从起始节点解析到结束节点。 无法解析特定的节点。 总体来说,它比其他两个要慢。

SAX and XMLPullParser : These use an object based approach and are similar in terms of memory and performance. SAX is similar to DOM in the context that it begins parsing from top to bottom and there is no way to parse only particular nodes. On the contrary, XMLPullParser can parse particular nodes.

SAX和XMLPullParser :它们使用基于对象的方法,并且在内存和性能方面相似。 在上下文中,SAX与DOM相似,它开始从上到下进行解析,并且无法仅解析特定的节点。 相反,XMLPullParser可以解析特定的节点。

An XML file consists of 4 major components.

XML文件包含4个主要组件。

  1. Prolog : The first line that contains the information about a file is prolog. Typically this is the line:

    序言 :包含有关文件信息的第一行是序言。 通常这是这行:
  2. Events : Events in an XML file include simple start and end tags and more

    事件 :XML文件中的事件包括简单的开始和结束标记等
  3. Text : It’s simple text in between two tags. Example: My Text</RandomTag

    文字 :两个标签之间的简单文字。 例如:我的文字</ RandomTag
  4. Attributes : Attributes are the additional properties of a tag that are present within the tag. Example : Some Text or nested tags

    属性 :属性是标签中存在的标签的其他属性。 示例:一些文本或嵌套标签

XMLPullParser (XMLPullParser)

XMLPullParser is the recommended android xml parser.

XMLPullParser是推荐的android xml解析器。

In this tutorial we’ll look to implement an XMLPullParser in our android application.

在本教程中,我们将寻求在我们的android应用程序中实现XMLPullParser。

Android XML解析器示例项目结构 (Android XML Parser Example Project Structure)

Android XML解析器代码 (Android XML Parser code)

We’ve created a assets directory inside the main directory and added an xml file there as shown below.

我们已经在主目录中创建了一个资产目录,并在其中添加了一个xml文件,如下所示。

<?xml version="1.0" encoding="utf-8"?>
<countries>
    <country id="1">
        <name>
            India
        </name>
        <capital>
            New Delhi
        </capital>
    </country>

    <country id="2">
        <name>
            Australia
        </name>
        <capital>
            Canberra
        </capital>
    </country>

    <country id="3">
        <name>
            USA
        </name>
        <capital>
            Washington, D.C.
        </capital>
    </country>

</countries>

Note: The “id” is the attribute.

注意:“ id”是属性。

The MainActivity.java is given below:

MainActivity.java如下所示:

package com.journaldev.xmlparsing;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView= (TextView)findViewById(R.id.text);

        XmlPullParserFactory pullParserFactory;

        try {
            pullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = pullParserFactory.newPullParser();

            InputStream in_s = getApplicationContext().getAssets().open("sample.xml");
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in_s, null);

            ArrayList<Country> countries=  parseXML(parser);

            String text="";

            for(Country country:countries)
            {

                text+= "id : "+country.getId()+" name : "+country.getName()+" capital : "+country.getCapital()+"\n";
            }

            textView.setText(text);



        } catch (XmlPullParserException e) {

            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private ArrayList<Country> parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
    {
        ArrayList<Country> countries = null;
        int eventType = parser.getEventType();
        Country country = null;

        while (eventType != XmlPullParser.END_DOCUMENT){
            String name;
            switch (eventType){
                case XmlPullParser.START_DOCUMENT:
                    countries = new ArrayList();
                    break;
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if (name.equals("country")){
                        country = new Country();
                        country.id=parser.getAttributeValue(null,"id");
                    } else if (country != null){
                        if (name.equals("name")){
                            country.name = parser.nextText();
                        } else if (name.equals("capital")){
                            country.capital = parser.nextText();
                        }
                    }
                    break;
                case XmlPullParser.END_TAG:
                    name = parser.getName();
                    if (name.equalsIgnoreCase("country") && country != null){
                        countries.add(country);
                    }
                    }
            eventType = parser.next();
        }

        return countries;

        }
}

XMLPullParser实例化 (XMLPullParser instantiation)

XMLPullParser can be instantiated in two ways.

XMLPullParser可以通过两种方式实例化。

  1. XmlPullParserFactory pullParserFactory;
    		try {
    			pullParserFactory = XmlPullParserFactory.newInstance();
    			XmlPullParser parser = pullParserFactory.newPullParser();
    		} catch (XmlPullParserException e) {
    
    			e.printStackTrace();
    		}

  2. XmlPullParser parser = Xml.newPullParser();

    Using switch statements and while loops we parse every tag and look for the relevant data and add the whole object to the ArrayList when the tag ends. We’ve just iterated through the complete ArrayList and appended the strings to display in the default TextView that’s present.

    The output of the application is given below.

    This brings an end to android xml parser tutorial. You can download the Android XML Parsing using XMLPullParser Project from the link given below.

    Reference: Android Official Doc

    XmlPullParser parser = Xml.newPullParser();

    使用switch语句和while循环,我们解析每个标签并查找相关数据,并在标签结束时将整个对象添加到ArrayList中 。 我们只是遍历了完整的ArrayList,并附加了字符串以显示在当前的默认TextView中。

    该应用程序的输出如下。

    这结束了android xml解析器教程。 您可以从下面提供的链接中使用XMLPullParser Project下载Android XML解析

    参考: Android官方文档

翻译自: https://www.journaldev.com/10653/android-xml-parser-xmlpullparser

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值