Android parsing xml from file

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.

An XML file starts with a prolog. The first line that contains the information about a file is prolog

An XML file has many events. Event could be like this. Document starts , Document ends, Tag start , Tag end and Text e.t.c

Apart from tags and events, and xml file also contains simple text. Such as GB is a text in the country tag.

Attributes are the additional properties of a tag such as value e.t.c

XML — Parsing

In the next step, we will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below −

The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream.Its syntax is given below −

The last step is to parse the XML. An XML file consist of events, Name, Text, AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax is given below −

The method getEventType returns the type of event that happens. e.g: Document start , tag start e.t.c. The method getName returns the name of the tag and since we are only interested in temperature , so we just check in conditional statement that if we got a temperature tag , we call the method getAttributeValue to return us the value of temperature tag.

Apart from the these methods, there are other methods provided by this class for better parsing XML files. These methods are listed below −

Sr.No Component & description
1

This method just Returns the number of attributes of the current start tag

This method returns the name of the attribute specified by the index value

This method returns the Returns the current column number, starting from 0.

This method returns Returns the current depth of the element.

Returns the current line number, starting from 1.

This method returns the name space URI of the current element.

This method returns the prefix of the current element

This method returns the name of the tag

This method returns the text for that particular element

This method checks whether the current TEXT event contains only whitespace characters.

Example

Here is an example demonstrating the use of XML DOM Parser. It creates a basic application that allows you to parse XML.

To experiment with this example, you can run this on an actual device or in an emulator.

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 −

Источник

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 :

Источник

Полный список

— парсим XML с помощью XmlPullParser

XmlPullParser – XML-парсер, который можно использовать для разбора XML документа. Принцип его работы заключается в том, что он пробегает весь документ, останавливаясь на его элементах. Но пробегает он не сам, а с помощью метода next. Мы постоянно вызываем метод next и с помощью метода getEventType проверяем, на каком элементе парсер остановился.

Основные элементы документа, которые ловит парсер:

Напишем приложение, которое возьмет xml-файл и разберет его на тэги и аттрибуты.

Project name: P0791_ XmlPullParser
Build Target: Android 2.3.3
Application name: XmlPullParser
Package name: ru.startandroid.develop.p0791xmlpullparser
Create Activity: MainActivity

В папке res создайте папку xml, и в ней создайте файл data.xml:

Это файл с описанием телефона Samsung Galaxy. Указаны его цена, характеристики экрана и возможные цвета корпуса. Данные выдуманы и могут не совпадать с реальностью 🙂

В onCreate мы получаем XmlPullParser с помощью метода prepareXpp и начинаем его разбирать. Затем в цикле while мы запускаем прогон документа, пока не достигнем конца — END_DOCUMENT. Прогон обеспечивается методом next в конце цикла while. В switch мы проверяем на каком элементе остановился парсер.

START_DOCUMENT – начало документа

START_TAG – начало тега. Выводим в лог имя тэга, его уровень в дереве тэгов (глубину) и количество атрибутов. Следующей строкой выводим имена и значения атрибутов, если они есть.

END_TAG – конец тэга. Выводим только имя.

TEXT – содержимое тэга

В методе prepareXpp мы подготавливаем XmlPullParser. Для этого вытаскиваем данные из папки res/xml. Это аналогично вытаскиванию строк или картинок – сначала получаем доступ к ресурсам (getResources), затем вызываем метод, соответствующий ресурсу. В нашем случае это — метод getXml. Но возвращает он не xml-строку , а готовый XmlPullParser.

Все сохраним и запустим приложение.

START_DOCUMENT
START_DOCUMENT
START_TAG: name = data, depth = 1, attrCount = 0
START_TAG: name = phone, depth = 2, attrCount = 0
START_TAG: name = company, depth = 3, attrCount = 0
text = Samsung
END_TAG: name = company
START_TAG: name = model, depth = 3, attrCount = 0
text = Galaxy
END_TAG: name = model
START_TAG: name = price, depth = 3, attrCount = 0
text = 18000
END_TAG: name = price
START_TAG: name = screen, depth = 3, attrCount = 2
Attributes: multitouch = yes, resolution = 320×480,
text = 3
END_TAG: name = screen
START_TAG: name = colors, depth = 3, attrCount = 0
START_TAG: name = color, depth = 4, attrCount = 0
text = black
END_TAG: name = color
START_TAG: name = color, depth = 4, attrCount = 0
text = white
END_TAG: name = color
END_TAG: name = colors
END_TAG: name = phone
END_TAG: name = data
END_DOCUMENT
START_DOCUMENT
START_DOCUMENT
START_TAG: name = data, depth = 1, attrCount = 0
START_TAG: name = phone, depth = 2, attrCount = 0
START_TAG: name = company, depth = 3, attrCount = 0
text = Samsung
END_TAG: name = company
START_TAG: name = model, depth = 3, attrCount = 0
text = Galaxy
END_TAG: name = model
START_TAG: name = price, depth = 3, attrCount = 0
text = 18000
END_TAG: name = price
START_TAG: name = screen, depth = 3, attrCount = 2
Attributes: multitouch = yes, resolution = 320×480,
text = 3
END_TAG: name = screen
START_TAG: name = colors, depth = 3, attrCount = 0
START_TAG: name = color, depth = 4, attrCount = 0
text = black
END_TAG: name = color
START_TAG: name = color, depth = 4, attrCount = 0
text = white
END_TAG: name = color
END_TAG: name = colors
END_TAG: name = phone
END_TAG: name = data
END_DOCUMENT

START_DOCUMENT срабатывает два раза по неведомым мне причинам. Далее можно наблюдать, как парсер останавливается в начале каждого тега и дает нам информацию о нем: имя, уровень (глубина), количество атрибутов, имена и названия атрибутов, текст. Также он останавливается в конце тега и мы выводим имя. В конце парсер говорит, что документ закончен END_DOCUMENT.

Если xml у вас не в файле, а получен откуда-либо, то XmlPullParser надо создавать другим способом. Перепишем метод prepareXpp:

Здесь мы сами создаем парсер с помощью фабрики, включаем поддержку namespace (в нашем случае это не нужно, на всякий случай показываю) и даем парсеру на вход поток из xml-строки (укороченный вариант data.xml).

Все сохраним и запустим. Смотрим лог:

START_DOCUMENT
START_TAG: name = data, depth = 1, attrCount = 0
START_TAG: name = phone, depth = 2, attrCount = 0
START_TAG: name = company, depth = 3, attrCount = 0
text = Samsung
END_TAG: name = company
END_TAG: name = phone
END_TAG: name = data
END_DOCUMENT

Здесь уже START_DOCUMENT сработал один раз, как и должно быть. Ну и далее идут данные элементов документа.

Присоединяйтесь к нам в Telegram:

— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование

— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня

— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

Читайте также:  Как с компьютера обновить android
Оцените статью