1. Trang chủ
  2. » Công Nghệ Thông Tin

Android chapter18a reading XML data Using SAX and W3C Parsers

27 446 1
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Android – Reading XML Data Using SAX And W3C Parsers
Tác giả Victor Matos
Trường học Cleveland State University
Thể loại Bài viết
Năm xuất bản 2025
Thành phố Cleveland
Định dạng
Số trang 27
Dung lượng 780,17 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Android – Reading XML Files XML Data 11 • In this example we will read an XML file saved in the /re/xml folder.. Reading/Parsing a Resource KML File Using the XmlPullParser class to

Trang 1

Android Reading XML Data Using SAX and W3C Parsers

18A

Victor Matos

Cleveland State University

Notes are based on:

Trang 2

Extensible Markup Language (XML) is a set of rules for encoding

documents in a readable form

• Similar to HTML but <tagElements> are user-defined

It is defined in the XML Specification produced by the W3C

• XML's design goals emphasize transparency, simplicity, and

transportability over the Internet

• Example of XML-based languages include: RSS , Atom, SOAP,

and XHTML

• Several office productivity tools default to XML format for internal data

storage Example: Microsoft Office, OpenOffice.org, and Apple's iWork

Trang 3

1 XML is used for defining and documenting object classes

collection of complex employee elements, such as

<employee id=“…” title=“…” > </employee>

which lexically includes an “id” and “title” attributes

3 Employee may also hold other inner elements such as

“name”, “country”, “city”, and “zip”

XML Data http://www.w3.org

Trang 5

< Street > 507 20th Ave E Apt 2A </ Street >

< City > Seattle </ City >

Trang 6

<?xml version="1.0" ?>

< xs:schema xmlns:xs ="http://www.w3.org/2001/XMLSchema" elementFormDefault ="qualified"

attributeFormDefault ="unqualified" targetNamespace ="http://Employees" xmlns ="http://Employees">

< xs:complexType name ="Country">

< xs:simpleType name ="City">

< xs:restriction base ="xs:string">

< xs:minLength value ="1" />

< xs:maxLength value ="50" />

</ xs:restriction >

</ xs:simpleType >

< xs:simpleType name ="Zip">

< xs:restriction base ="xs:positiveInteger">

Only a fragment Lines removed

Trang 7

Reference: http://code.google.com/apis/kml/documentation/kml_tut.html

Trang 9

9

18 Android – Reading XML Files

XML Data

9

Example 2 Mapping with KML & Playing Golf

Typical Distances for (Good) Amateur Players

Reference: Cartoon by Lash Leroux available at http://www.golfun.net/lash3.htm

Trang 11

11

18 Android – Reading XML Files

XML Data

11

• In this example we will read an XML file saved in the /re/xml folder

The example file contains a set of place-markers around a golf course

A SAX (Simple API for XML) XmlPullParser is used to scan the

document using the next() method and detect the main eventTypes

START_TAG TEXT

END_TAG END_DOCUMENT

When the beginning of a tag is recognized, we use the getName()

method to grab the tag name

We use the method getText() to extract data after TEXT event

SAX

Simple API for XML

Reference: http://www.saxproject.org/

Trang 12

12

18 Android – Reading XML Files

XML Data

12

Attributes from an element can be extracted using the methods:

.getAttributeCount()

getAttributeName()

getAttributeValue()

For the example below:

< name par= " 4 " yards= " 390 " > Tee Hole 1 </ name >

Trang 13

13

18 Android – Reading XML Files

XML Data

13

Example 2 Reading/Parsing a Resource KML File

Using the XmlPullParser class to generate scanner/parser to traverse an XML document

SAX

Simple API for XML

Trang 14

Example 2 Reading a Resource KML File (code)

<?xml version="1.0" encoding = "utf-8" ?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

Trang 15

Example 2 Reading a Resource KML File (code)

// demonstrates the reading of XML resource files In this case

// containing mapping data (kml) holding inner elements as well

// as common <node> text </node> tags

@Override

public void onClick(View v) {

String nodeText = "";

String nodeName = "“;

Trang 16

if (eventType == XmlPullParser. START_DOCUMENT ) {

stringBuilder.append( "Start document \n" );

} else if (eventType == XmlPullParser. END_DOCUMENT ) {

stringBuilder.append( "End document \n" );

} else if (eventType == XmlPullParser. START_TAG ) {

nodeName = parser.getName();

stringBuilder.append( "Start tag:\t" + parser.getName() + "\n" ); innerAttributes(parser, stringBuilder);

} else if (eventType == XmlPullParser. END_TAG ) {

stringBuilder.append( "End tag: \t" + parser.getName() + "\n" ); } else if (eventType == XmlPullParser. TEXT ) {

if (nodeName.equals( "name" )) stringBuilder.append( "\n" );

nodeText = parser.getText();

stringBuilder.append( "Text: \t\t" + parser.getText() + "\n" ); tokenizeText(parser, stringBuilder, nodeName);

} txtMsg setText(stringBuilder.toString());

} } catch (Exception e) {

Log.e("<<PARSING>>" , e.getMessage());

} } });

} //onCreate

SAX

Simple API for XML

Trang 17

17

18 Android – Reading XML Files

XML Data

17

Example 2 Reading a Resource KML File (code)

// trying to detect inner elements nested around gcData tag

String name = parser.getName();

if (!name.equals( "gcPlace" )) return ;

String gcName = null ;

String gcCity = null ;

String gcState= null ;

// Processing a fragment of the type:

// <gcPlace gcName="Manakiki GC" gcCity="Willoughby" gcState="OH" ></gcPlace>

if ((name != null ) && name.equals( "gcPlace" )) {

int size = parser.getAttributeCount();

for ( int i = 0; i < size; i++) {

String attrName = parser.getAttributeName(i);

String attrValue = parser.getAttributeValue(i);

if ((attrName != null ) && attrName.equals( "gcName" )) {

if ((gcName != null ) && (gcCity != null ) && (gcState != null ) ) {

}//innerElements

SAX

Simple API for XML

Trang 18

18

18 Android – Reading XML Files

XML Data

18

Example 2 Reading a Resource KML File (code)

nodeName){

// interpreting text enclosed in a “coordinates” tag String text = parser.getText();

if ((text== null ) || (!nodeName.equals( "coordinates" ))) return ;

// parsing <coordinates> latitude, longitude, altitude </coordinates>

String [] loc = text.split(",");

text = "<<LOC>> " + nodeName + " Lon: " + loc[0] + " Lat: " + loc[1] + "\n"; stringBuilder.append(text);

Trang 19

19

18 Android – Reading XML Files

XML Data

19

In this example we read the same XML data of the previous example; however the

file is stored in the SD card

Rather than stepping through the SAX eventTypes recognized by an XmlPullParser,

a W3C DocumentBuilder parser will be used here

The XML file is given to the W3C parser to construct an equivalent tree

Elements from the XML file are represented in the parse-tree as NodeLists These ArrayList-like collections are made with the getElementsByTagName() method

An individual node from a NodeList could be explored using the methods:

.item(i), getName() , getValue() , getFirstChild() , getAttributes(),…

Note: The World Wide Web Consortium (W3C.org) is an “international community that develops open standards to ensure the

long-term growth of the Web”

Trang 21

21

18 Android – Reading XML Files

XML Data

21

Example 3 Reading an XML file from the SD card (code)

<? xml version ="1.0" encoding = "utf-8" ?>

< LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android"

Trang 22

public void onConfigurationChanged(Configuration newConfig) {

// needed to avoid re-starting app on orientation changes

Example 3 Reading an XML file from the SD card (code)

NOTE: You need to modify the Manifest to stop reorientation Add the

following attributes to the <activity … > element

android:screenOrientation="portrait"

android:configChanges="keyboardHidden|orientation"

Trang 23

btnGo = (Button) findViewById(R.id.button1 );

btnGo.setOnClickListener(new OnClickListener() {

InputStream is = new FileInputStream(kmlFile);

DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance()

newDocumentBuilder();

Document document = docBuilder.parse(is);

NodeList listNameTag = null ;

NodeList listCoordinateTag = null ;

Trang 24

24

18 Android – Reading XML Files

XML Data

24

Example 3 Reading an XML file from the SD card (code)

StringBuilder str = new StringBuilder();

// dealing with 'name' tagged elements

listNameTag = document.getElementsByTagName( "name" );

// showing 'name' tags

for ( int i = 0; i < listNameTag.getLength(); i++) {

Node node = listNameTag.item(i);

int size = node.getAttributes().getLength();

String text = node.getTextContent();

str.append( "\n " + i + ":- name text > " + text);

// get all attributes of the current ‘name’ element (i-th hole)

for ( int j = 0; j < size; j++) {

String attrName = node.getAttributes().item(j).getNodeName();

String attrValue = node.getAttributes().item(j).getNodeValue();

str.append( "\n\t attr info-" + i + "-" + j + ": "

+ attrName + " " + attrValue);

}

}

Trang 25

25

18 Android – Reading XML Files

XML Data

25

Example 3 Reading an XML file from the SD card (code)

// dealing with 'coordinates' tagged elements

listCoordinateTag = document.getElementsByTagName("coordinates");

// showing 'coordinates' tags

for ( int i = 0; i < listCoordinateTag.getLength(); i++) {

String coordText = listCoordinateTag.item(i).getFirstChild()

Trang 26

26

18 Android – Reading XML Files

XML Data

26

Example 3 Reading an XML file from the SD card (code)

private int distanceYards(GolfMarker gm){

// calculating distance (yards) between two coordinates

return intDistance;

}

NOTE: calculating distance between two locations

Not implemented yet …

Ngày đăng: 16/03/2014, 23:40

TỪ KHÓA LIÊN QUAN