- Android — XML Parser
- XML — Elements
- XML — Parsing
- Example
- XML Pull Parser
- Android: Simple XMLPullParser Tutorial
- Project Description
- Environment Used
- Prerequisites
- Create Android Project
- Create XML file
- strings.xml
- XML layout files
- main layout file (main.xml)
- ListView item layout file (list_item.xml)
- Create Bean class
- Employee.java
- Create XMLPullParserHandler class
- Create XMLPullParserActivity class
- AndroidManifest.xml
- Output
- Project Folder Structure
- Parsing XML data in Android Apps
- Creating a simple User Interface
- Defining XML data to parse
- Creating a Player POJO
- Preparing the XML Parser
- Parsing the XML data
- Displaying the XML data
- Our App in Action
Android — XML Parser
XML stands for Extensible Mark-up Language.XML is a very popular format and commonly used for sharing data on the internet. This chapter explains how to parse the XML file and extract necessary information from it.
Android provides three types of XML parsers which are DOM,SAX and XMLPullParser. Among all of them android recommend XMLPullParser because it is efficient and easy to use. So we are going to use XMLPullParser for parsing XML.
The first step is to identify the fields in the XML data in which you are interested in. For example. In the XML given below we interested in getting temperature only.
XML — Elements
An xml file consist of many components. Here is the table defining the components of an XML file and their description.
Sr.No | Component & description | ||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
Sr.No | Method & description | |||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
Steps | Description |
---|---|
1 | You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. |
2 | Modify src/MainActivity.java file to add necessary code. |
3 | Modify the res/layout/activity_main to add respective XML components |
4 | Create a new XML file under Assets Folder/file.xml |
5 | Modify AndroidManifest.xml to add necessary internet permission |
6 | Run the application and choose a running android device and install the application on it and verify the results |
Following is the content of the modified main activity file MainActivity.java.
Following is the content of Assets/file.xml.
Following is the modified content of the xml res/layout/activity_main.xml.
Following is the content of AndroidManifest.xml file.
Let’s try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Источник
XML Pull Parser
Рассмотрим парсер XML Pull Parser. Парсер позволяет разбирать XML-документы за один проход. После прохода парсер представляет элементы документа в виде последовательности событий и тегов. На данный момент именно его рекомендует использовать Google в Android-приложениях.
Посмотрим на документ глазами парсера. Он видит следующие элементы документа:
- START_DOCUMENT – начало документа
- START_TAG – начало тега
- TEXT – содержимое элемента
- END_TAG – конец тега
- END_DOCUMENT – конец документа
Каждый документ начинается с события START_DOCUMENT и заканчивается событием END_DOCUMENT. Позиция внутри документа представлена в виде текущего события, которое можно определить, вызвав метод getEventType().
Для последовательного перехода по тегам нужно вызывать метод next(), который перемещает нас по цепочке совпавших (иногда вложенных) событий START_TAG и END_TAG. Можно извлечь имя любого тега при помощи метода getName() и получить текст между каждым набором тегов с помощью метода getNextText().
Чтобы упаковать статический XML-документ вместе с вашим приложением, поместите его в каталог res/xml/. Вы получите возможность обращаться в коде программы к этому документу (операции чтения и записи). Рассмотрим загрузку XML-документа произвольной структуры из ресурсов в код программы.
Создадим пример приложения, способный читать список имён котов и их домашних телефонов, определённых в XML-файле.
В каталоге res создайте подкаталог xml, в котором будет располагаться наш ХМL-файл. В этом файле мы напишем список котов и телефонов, и сохраним его под именем contacts.xml.
Добавим в разметку компонент ListView:
Загрузить созданный файл contacts.xml можно следующим образом:
Метод getXml() возвращает XmlPullParser, который может прочитать загруженный XML-документ в цикле while:
Как это происходит? Запускаем цикл while с условием, что он будет работать пока не достигнет конца документа, т.е. закрывающего корневого тега (END_DOCUMENT).
Далее парсер начинает перемещаться по тегам. Мы говорим ему, что если (if) встретишь тег contact, то передай ему привет добавь в массив текст из первого атрибута. И из второго атрибута. И из третьего атрибута. После чего даём пинка парсеру с помощью метода next(), чтобы он шёл искать дальше.
У элемента contact мы определили три атрибута first_name, last_name и phone, которые загружаются в список. Первые два атрибута разделяем пробелом, а третий атрибут (номер телефона) выводим на новой строке.
Полностью код выглядит следующим образом:
Для закрепления материала изменим структуру документа. Пусть он будет выглядеть следующим образом:
А теперь напишем код, который будет отслеживать все теги при разборе документа и выводить результат в лог.
Принцип тот же. Только на этот раз результат мы не выводим в списке, а просто выводим в лог. Для удобства совместил картинку документа и лог на одном экране, чтобы наглядно показать работу парсера.
Если вы будете брать документ не из ресурсов, а из файла с внешнего накопителя, то получение парсера для обработки документа будет иным:
Это самый простой пример использования парсера для чтения документа из ресурсов. В реальных приложениях вам придётся получать информацию с файла, который находится в интернете.
Источник
Android: Simple XMLPullParser Tutorial
There are three types of Android XML parsers – DOM, SAX and XmlPullParser. You can use DOM and SAX parser API which are provided by Java platform. In addition to these two parsers, Android provides XmlPullParser which is similar to StAX parser and is also the recommended XML parsing in Android. This Android XML parsing example explains how to parse a simple XML using Android XMLPullParser.
Project Description
- This Android 4 XmlPullParser example shows how to parse a simple XML containing employee details and display the result in ListView.
- This example stores XML file in project’s assets folder and opens the file as InputStream using AssetManager .
- When the main activity is loaded, it parses the XML and displays the employee details in ListView.
Environment Used
- JDK 6 (Java SE 6)
- Eclipse Juno IDE for Java EE Developers
- Android SDK 4.0.3 / 4.2 Jelly Bean
- Android Development Tools (ADT) Plugin for Eclipse (ADT version 21.0.0)
- Refer this link to setup the Android development environment
Prerequisites
Create Android Project
- Create a new Android Project and enter the Application name as SimpleXMLPullParser.
- Project name as SimpleXMLPullParser.
- Enter the package name as com.theopentutorials.xml.activities.
- Enter the Activity name as XMLPullParserActivity.
- Enter the Layout name as main.
- Click Finish.
Create XML file
In the project’s assets folder, create a new XML file and name it as “employees.xml” and copy the following.
strings.xml
Open res/values/strings.xml and replace it with following content.
XML layout files
main layout file (main.xml)
This file defines a layout for displaying the result of XMLPullParser in ListView widget. Open main.xml file in res/layout and copy the following content.
ListView item layout file (list_item.xml)
Create Bean class
Employee.java
Create a new Java class “Employee.java” in package “com.theopentutorials.android.beans” and copy the following code.
Create XMLPullParserHandler class
Create a new Java class “XMLPullParserHandler.java” in package “com.theopentutorials.android.xml” and copy the following code.
XML Pull Parser is an interface that defines parsing functionality provided in XMLPULL V1 API. This is a simple interface – parser consists of one interface, one exception and one factory to create parser.
Steps required to parse a XML using XML pull parser are,
- get instance of XMLPULL facotry as shown in line 30
- (optional step) by default factory will produce parsers that are not namespace aware; to change setNamespaceAware() function must be called as shown in line 31
- create an instance of the parser as shown in line 32
- Then set parser input as shown in line 34
- and now start parsing. Typical XMLPULL applicaition will repeatedly call next() function (line 71) to retrieve next event, process event until the event is END_DOCUMENT.
Create XMLPullParserActivity class
Now lets create the activity class “XMLPullParserActivity” in package “com.theopentutorials.android.activities“.
AndroidManifest.xml
Output
Run your application
Project Folder Structure
The complete folder structure of this example is shown below.
Источник
Parsing XML data in Android Apps
Jun 28, 2018 · 4 min read
JSON is become a very widespread format for the Web Services but in some cases, you would have to parse data in the good old XML format. In that tutorial, you are going to learn how to parse a XML file on Android.
Note that there are various XML parses available in the Android SDK in standard. Thus, you can use the following solutions :
- XMLPullParser API
- DOM Parser API
- SAX Parser API
As usual, each parser has its advantages and drawbacks.
The recommendation on Andr o id is to use the XMLPullParser API which consumes less memory than the DOM Parser API which loads the complete XML file in memory before parsing it.
So, in this tutorial, we will use the XMLPullParser API. Note that you can also discover this tutorial in video on YouTube :
Creating a simple User Interface
To display the parsed XML data, we need to create a simple User Interface. It will consist in a simple TextView centered on the screen :
Defining XML data to parse
Then, we define some XML data to parse inside a file under the assets directory of our Android project. This file will be named data.xml and will contain some NBA players with data like name, age and position played :
Creating a Player POJO
To map the data for each player, we create a Player POJO (Plain Old Java Object) :
Preparing the XML Parser
The first step is to load the XML file from the assets of our Android Application. For that, we define a parseXML method. We create a new instance of the XMLPullParserFactory class. Then, we create a new XMLPullParser instance by calling the newPullParser method of the XMLPullParserFactory got previously.
We got an InputStream on the XML file by calling the open method of the AssetManager instance. With that instance, we can set the input on the XMLPullParser instance. It gives us the following code :
Parsing the XML data
Now, we need to parse the XML data. The parsing will be processed in the processParsing method. We start by getting the current event type from the parser by calling the getEventType method.
Then, we enter in a loop while the event type is different of the XmlPullParser.END_DOCUMENT constant. In the loop, when we meet a XmlPullParser.START_TAG event type, we get the name of the current tag by calling the getName method.
When we have a player tag, we create a new Player instance and we add it in an ArrayList of Player. This list will be used to store all the players read from the XML file.
If the current player is not null, we are reading data for a player. We have to check if the tag is name, age or position. For each case, we call the nextText method of the parser to get the value associated to the tag. Then, we set the value on the current player.
At the end of the loop, we have stored all the players from the XML file on the ArrayList of Player. Note that just before the end of the loop, you need to call the next method of the parser to pass to the following event.
It gives us the following code :
Displaying the XML data
The last step is also the simplest. We need to display the players in our TextView via the printPlayers called at the end of the processParsing method.
In that method, we iterate on the ArrayList of Player and for each player we add its properties (name, age and position) on a StringBuilder instance. Finally, we display the text on the TextView by calling its setText method with the value of the StringBuilder instance.
It gives us the following complete code for the MainActivity :
Our App in Action
Best part of the tutorial is coming since it’s time to put our App in Action. When, you will launch the Application, you should have the following result :
That’s all for that tutorial.
To discover more tutorials on Android development, don’t hesitate to subscribe to the SSaurel’s Channel on YouTube :
Источник