Anda di halaman 1dari 16

Activity

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the
Activity class takes care of creating a window for you in which you can place your UI
withsetContentView(View). While activities are often presented to the user as full-screen windows, they can
also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded
inside of another activity (using ActivityGroup). There are two methods almost all subclasses of Activity
will implement:
Activity Lifecycle
Activities in the system are managed as an activity stack. When a new activity is started, it is placed on the
top of the stack and becomes the running activity -- the previous activity always remains below it in the
stack, and will not come to the foreground again until the new activity exits.
An activity has essentially four states:

If an activity is in the foreground of the screen (at the top of the stack), it is active or running.

If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has
focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and
member information and remains attached to the window manager), but can be killed by the system in
extreme low memory situations.

If an activity is completely obscured by another activity, it is stopped. It still retains all state and
member information, however, it is no longer visible to the user so its window is hidden and it will often
be killed by the system when memory is needed elsewhere.

If an activity is paused or stopped, the system can drop the activity from memory by either asking it
to finish, or simply killing its process. When it is displayed again to the user, it must be completely
restarted and restored to its previous state.

The following diagram shows the important state paths of an Activity. The square rectangles represent
callback methods you can implement to perform operations when the Activity moves between states. The
colored ovals are major states the Activity can be in.

The entire lifecycle of an activity is defined by the following Activity methods. All of these are hooks that
you can override to do appropriate work when the activity changes state. All activities will
implement onCreate(Bundle) to do their initial setup; many will also implement onPause() to commit
changes to data and otherwise prepare to stop interacting with the user. You should always call up to your
superclass when implementing these methods.
public

class

Activity
protected

void
protected
protected
protected
protected

extends
ApplicationContext
{
onCreate(Bundle
savedInstanceState);
void
void
void
void

onStart();
onRestart();
onResume();
onPause();

protected

void

protected

void

onStop();
onDestroy();

In general the movement through an activity's lifecycle looks like this:


Method

Description

Killable?

Next

onCreate()

Called when the


activity
is
first
created.
This
is
where you should do
all of your normal
static set up: create
views, bind data to
lists,
etc.
This
method also provides
you with a Bundle
containing
the
activity's previously
frozen state, if there
was one.
Always
followed
by onStart().

No

onStart()

onRestart()

Called after your


activity has been
stopped, prior to it
being started again.
Always
followed
by onStart()

No

onStart()

onStart()

Called when the


activity is becoming
visible to the user.
Followed
by onResume() if the
activity comes to the
foreground,
or onStop() if
it
becomes hidden.

No

onResume()or onSt
op()

onResum
e()

Called when the


activity will start
interacting with the
user. At this point
your activity is at the
top of the activity
stack, with user input
going to it.
Always
followed
by onPause().

No

onPause()

onPause()

Called

Pre-

onResume()or

when

the

Method

onStop()

onDestroy()

Description

Killable?

Next

system is about to
start resuming a
previous
activity.
This is typically used
to commit unsaved
changes to persistent
data, stop animations
and other things that
may be consuming
CPU,
etc.
Implementations of
this method must be
very quick because
the next activity will
not be resumed until
this method returns.
Followed
by
either onResume() if
the activity returns
back to the front,
or onStop() if
it
becomes invisible to
the user.

HONEYCO
MB

onStop()

Called when the


activity is no longer
visible to the user,
because
another
activity has been
resumed
and
is
covering this one.
This may happen
either because a new
activity is being
started, an existing
one is being brought
in front of this one,
or this one is being
destroyed.
Followed
by
either onRestart() if
this
activity
is
coming
back
to
interact with the user,
oronDestroy() if this
activity is going
away.

Yes

onRestart()or
onDestroy()

The final call you


receive before your
activity is destroyed.
This can happen
either because the
activity is finishing

Method

Description

Killable?

Next

(someone
calledfinish() on it, or
because the system is
temporarily
destroying
this
instance
of
the
activity
to
save
space.
You
can
distinguish between
these two scenarios
with
the isFinishing() met
hod.

Process lifecycle
The Android system tries to maintain an application process for as long as possible, but eventually needs to
remove old processes to reclaim memory for new or more important processes. To determine which
processes to keep and which to kill, the system places each process into an "importance hierarchy" based on
the components running in the process and the state of those components. Processes with the lowest
importance are eliminated first, then those with the next lowest importance, and so on, as necessary to
recover system resources.
There are five levels in the importance hierarchy. The following list presents the different types of processes
in order of importance (the first process is most important and is killed last):
1.

Foreground process

A process that is required for what the user is currently doing. A process is considered to be in the
foreground if any of the following conditions are true:
o
o

It hosts an Activity that the user is interacting with (the Activity's onResume() method has
been called).
It hosts a Service that's bound to the activity that the user is interacting with.

It
hosts
a Service that's
called startForeground().

It hosts a Service that's executing one of its lifecycle callbacks (onCreate(), onStart(),
oronDestroy()).

running

"in

the

foreground"the

service

has

It hosts a BroadcastReceiver that's executing its onReceive() method.

Generally, only a few foreground processes exist at any given time. They are killed only as a last resort
if memory is so low that they cannot all continue to run. Generally, at that point, the device has reached a
memory paging state, so killing some foreground processes is required to keep the user interface
responsive.
2.

Visible process
A process that doesn't have any foreground components, but still can affect what the user sees on screen.
A process is considered to be visible if either of the following conditions are true:
o

It hosts an Activity that is not in the foreground, but is still visible to the user
(its onPause()method has been called). This might occur, for example, if the foreground activity
started a dialog, which allows the previous activity to be seen behind it.
It hosts a Service that's bound to a visible (or foreground) activity.

A visible process is considered extremely important and will not be killed unless doing so is required to
keep all foreground processes running.
3.

Service process
A process that is running a service that has been started with the startService() method and does not fall
into either of the two higher categories. Although service processes are not directly tied to anything the
user sees, they are generally doing things that the user cares about (such as playing music in the
background or downloading data on the network), so the system keeps them running unless there's not
enough memory to retain them along with all foreground and visible processes.

4.

Background process
A process holding an activity that's not currently visible to the user (the activity's onStop() method has
been called). These processes have no direct impact on the user experience, and the system can kill them
at any time to reclaim memory for a foreground, visible, or service process. Usually there are many
background processes running, so they are kept in an LRU (least recently used) list to ensure that the
process with the activity that was most recently seen by the user is the last to be killed. If an activity
implements its lifecycle methods correctly, and saves its current state, killing its process will not have a
visible effect on the user experience, because when the user navigates back to the activity, the activity

restores all of its visible state. See the Activities document for information about saving and restoring
state.
5.

Empty process
A process that doesn't hold any active application components. The only reason to keep this kind of
process alive is for caching purposes, to improve startup time the next time a component needs to run in
it. The system often kills these processes in order to balance overall system resources between process
caches and the underlying kernel caches.

Android ranks a process at the highest level it can, based upon the importance of the components currently
active in the process. For example, if a process hosts a service and a visible activity, the process is ranked as
a visible process, not a service process.
In addition, a process's ranking might be increased because other processes are dependent on ita process
that is serving another process can never be ranked lower than the process it is serving. For example, if a
content provider in process A is serving a client in process B, or if a service in process A is bound to a
component in process B, process A is always considered at least as important as process B.
Because a process running a service is ranked higher than a process with background activities, an activity
that initiates a long-running operation might do well to start a service for that operation, rather than simply
create a worker threadparticularly if the operation will likely outlast the activity. For example, an activity
that's uploading a picture to a web site should start a service to perform the upload so that the upload can
continue in the background even if the user leaves the activity. Using a service guarantees that the operation
will have at least "service process" priority, regardless of what happens to the activity. This is the same
reason that broadcast receivers should employ services rather than simply put time-consuming operations in
a thread.

An intent is an abstract description of an operation to be performed. It can be used withstartActivity to


launch an Activity, broadcastIntent to send it to any interestedBroadcastReceiver components,
and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a
background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications.
Its most significant use is in the launching of activities, where it can be thought of as the glue between

activities. It is basically a passive data structure holding an abstract description of an action to be


performed.Intent Structure
The primary pieces of information in an intent are:

action -The
general
action
to
as ACTION_VIEW, ACTION_EDIT, ACTION_MAIN, etc.

be

performed,

such

data -- The data to operate on, such as a person record in the contacts database, expressed as aUri.

Some examples of action/data pairs are:

ACTION_VIEW content://contacts/people/1 -- Display information about the person whose


identifier is "1".

ACTION_DIAL content://contacts/people/1 -- Display the phone dialer with the person filled in.

ACTION_VIEW tel:123 -- Display the phone dialer with the given number filled in. Note how the
VIEW action does what is considered the most reasonable thing for a particular URI.

ACTION_DIAL tel:123 -- Display the phone dialer with the given number filled in.

ACTION_EDIT content://contacts/people/1 -- Edit information about the person whose identifier is


"1".

ACTION_VIEW content://contacts/people/ -- Display a list of people, which the user can browse
through. This example is a typical top-level entry into the Contacts application, showing you the list of
people. Selecting a particular person to view would result in a new intent
{ ACTION_VIEWcontent://contacts/people/N } being used to start an activity to display that person.

In addition to these primary attributes, there are a number of secondary attributes that you can also include
with an intent:

category -Gives
additional
information
about
the
action
to
execute.
For
example,CATEGORY_LAUNCHER means it should appear in the Launcher as a top-level application,
whileCATEGORY_ALTERNATIVE means it should be included in a list of alternative actions the user
can perform on a piece of data.

type -- Specifies an explicit type (a MIME type) of the intent data. Normally the type is inferred
from the data itself. By setting this attribute, you disable that evaluation and force an explicit type.

component -- Specifies an explicit name of a component class to use for the intent. Normally this is
determined by looking at the other information in the intent (the action, data/type, and categories) and
matching that with a component that can handle it. If this attribute is set then none of the evaluation is
performed, and this component is used exactly as is. By specifying this attribute, all of the other Intent
attributes become optional.

extras -- This is a Bundle of any additional information. This can be used to provide extended
information to the component. For example, if we have a action to send an e-mail message, we could also
include extra pieces of data here to supply a subject, body, etc.

Intent Resolution
There are two primary forms of intents you will use.

Explicit
Intents have
specified
a
component
(via setComponent(ComponentName) orsetClass(Context, Class)), which provides the exact class to be
run. Often these will not include any other information, simply being a way for an application to launch
various internal activities it has as the user interacts with the application.

Implicit Intents have not specified a component; instead, they must include enough information for
the system to determine which of the available components is best to run for that intent.

When using implicit intents, given such an arbitrary intent we need to know what to do with it. This is
handled by the process of Intent resolution, which maps an Intent to an Activity, BroadcastReceiver,
or Service (or sometimes two or more activities/receivers) that can handle it.
The intent resolution mechanism basically revolves around matching an Intent against all of the <intentfilter> descriptions in the installed application packages. (Plus, in the case of broadcasts,
anyBroadcastReceiver objects explicitly registered with registerReceiver(BroadcastReceiver, IntentFilter).)
More details on this can be found in the documentation on the IntentFilter class.
There are three pieces of information in the Intent that are used for resolution: the action, type, and category.
Using this information, a query is done on the PackageManager for a component that can handle the intent.
The appropriate component is determined based on the intent information supplied in
the AndroidManifest.xml file as follows:

The action, if given, must be listed by the component as one it handles.

The type is retrieved from the Intent's data, if not already supplied in the Intent. Like the action, if a
type is included in the intent (either explicitly or implicitly in its data), then this must be listed by the
component as one it handles.

For data that is not a content: URI and where no explicit type is included in the Intent, instead
thescheme of the intent data (such as http: or mailto:) is considered. Again like the action, if we are
matching a scheme it must be listed by the component as one it can handle.

The categories, if supplied, must all be listed by the activity as categories it handles. That is, if you
include the categories CATEGORY_LAUNCHER and CATEGORY_ALTERNATIVE, then you will
only resolve to components with an intent that lists both of those categories. Activities will very often
need to support the CATEGORY_DEFAULT so that they can be found by Context.startActivity().

What Intent is
In our case Intent is an object in which we specify, which Activity we need to invoke. After it we pass this
Intent-object to startActivity method, which finds the corresponding Activity and shows it. When creating an
Intent we have used Intent(Context packageContext, Class cls) constructor with two parameters.

The first parameter is Context. If you remember, when we created View in one of our previous lessons, we
have also used a Context object. Activity is a subclass of Context, thats why we can use Activity as a
Context object - this. To be short, Context is an object that grants access to basic application functions such
as: access to resources, file system, Activity invocation, etc. I guess in future we will explore examples
where we will see explicitly what Context is used for and how it is used.
The second parameter is a class name. I will remind that when creating Activity, we specify its class name in
the manifest-file. Now if we specify the same class for Intent - the system will look up the corresponding
Activity in the manifest-file and show it.
You can check it easily. We will delete the record about the Activity from the manifest-file and will try to
invoke it afterwards. Open the project from previous lesson P0211_TwoActivity, open the manifest-file,
Application tab and delete the record about ActivityTwo using the Remove button. Save everything, run the
application and try to invoke Activity using "Go to Activity Two" button. An error will occur. If you check
the log, we can see the following text:
ERROR/AndroidRuntime(367): android.content.ActivityNotFoundException: Unable to find explicit
activity
class
{ru.startandroid.develop.p0211twoactivity/ru.startandroid.develop.p0211twoactivity.ActivityTwo}; have you
declared this activity in your AndroidManifest.xml?
(Logs - LogCat tab in Eclipse. If it is not visible, go to Window -> Show View -> Other, Android folder ->
LogCat)
System tells us, that it not found such Activity class and kindly hints us that it may be not declared in the
manifest file. Register Activity in the manifest-file again, save everything and run the application. It must
work now.
Explicit invocation
Invoking Activity with such an Intent is an explicit invocation. That is, using the class we explicitly specify
which Activity we would like to see. It is usually used inside one application. It can be illustrated in the
following way:
We create an Intent here and pass it Class_B class as a parameter. After this we invoke startActivity method
with created Intent as a parameter. Method checks if Activity (with Class_B) is present in AndroidManifest,
if yes it displays the Activity. It is all in the bounds of single application.
Implicit invocation
There is also an implicit Activity invocation. The difference is that for creating an Intent we use not a class
object, but fill action, data, category parameters with specific values. The combination of these values
defines a goal which we are trying to accomplish. For example, sending a letter, opening a link, editing some
text, viewing an image, calling a specific number and so on. By-turn we specify an Intent Filter for the
Activity - it is a set of the same parameters: action, data, category (but the values are its own, they depend on
what Activity is capable of doing). And if the parameters of our intent match the conditions of this filter, the
activity is invoked. But now the search goes through all the Activities in the system. If several Activities are
found, the system gives you a choice, which application exactly would you like to use. It can be illustrated
as following:
Intent is created in Application_1, action, data, category parameters are filled. Lets name this set of
parameters Param_C for convenience. Using startActivity, this Intent will be sent to look for an appropriate
Activity, which will be able to accomplish what we need (that is what is defined by Param_C). There are

different applications in the system, and each of them has several Activities. For some of them an Intent
Filter is defined (Param_A, Param_B sets and so on), for some it is not. startActivity method matches the set
of parameters from Intent and sets of parameters of Intent Filter for each Activity. If the sets match
(Param_C) for both, the Activity is considered appropriate.
If, in the end, only one Activity is found - it is displayed. If there are several Activities found, the user is
given a list, from which he can choose which application to use.
For example, if there are several music players installed on the system and you open an mp3 file, the system
will show you the list of Activities, that are able to play music and will ask you to choose which one of them
to use. And those Activities that can edit text, show pictures, make calls and so on, will be ignored.

If there is no Intent Filter for an Activity (Activity_24 on the picture), in this case Intent with parameters will
not fit it in any way and the Activity will also be ignored.
If trying to find an analogy - Intent can be compared to a key and Intent Filter to a lock, which hides our
awesome Activity )))
We will gradually find out nuances of this mechanism and values, using which you can fill action, data and
category in Intent and Intent Filter. For now, it is important to understand, that in case of implicit invocation,
one application sends an Intent and all other applications check this Intents parameters with their own
Activity -> Intent Filter. Intent is a basic concept of Android system and you can not do without it. It is used
not only for Activity. But we will talk about it later.
This is it, I wanted to write a few introductory words but came up with quite detailed explanation with
illustrations and examples ) Hope Ive managed to deliver the idea of Intent concept. In further lessons we
will have some practice and make our knowledge more solid.

App Manifest

Every application must have an AndroidManifest.xml file (with precisely that name) in its root
directory. The manifest file provides essential information about your app to the Android system, which the
system must have before it can run any of the app's code.
Among other things, the manifest file does the following:

It names the Java package for the application. The package name serves as a unique identifier for the
application.

It describes the components of the application, which include the activities, services, broadcast
receivers, and content providers that compose the application. It also names the classes that implement
each of the components and publishes their capabilities, such as the Intent messages that they can handle.
These declarations inform the Android system of the components and the conditions in which they can be
launched.

It determines the processes that host the application components.


It declares the permissions that the application must have in order to access protected parts of the
API and interact with other applications. It also declares the permissions that others are required to have
in order to interact with the application's components.

It lists the Instrumentation classes that provide profiling and other information as the application
runs. These declarations are present in the manifest only while the application is being developed and are
removed before the application is published.

It declares the minimum level of the Android API that the application requires.

It lists the libraries that the application must be linked against.

Context

Interface to global information about an application environment. This is an abstract class whose
implementation is provided by the Android system. It allows access to application-specific
resources and classes, as well as up-calls for application-level operations such as launching
activities, broadcasting and receiving intents, etc.
Context is context of current state of the application/object.It s an entity that represents various
environment data . Context helps the current activity to interact with out side android environment
like local files, databases, class loaders associated to the environment, services including systemlevel services, and more.
A Context is a handle to the system . It provides services like resolving resources, obtaining
access to databases and preferences, and so on. An android app has activities. Its like a handle
to the environment your application is currently running in. The activity object inherits the Context
object.
It lets newly created objects understand what has been going on. Typically you call it to get
information regarding another part of your program (activity, package/application).

Fir de execuie
De la Wikipedia, enciclopedia liber
Conceptul de thread (fir de execuie) definete cea mai mic unitate de procesare ce poate fi
programat spre execuie de ctre sistemul de operare. Este folosit n programare pentru a
eficientiza execuia programelor, executnd por iuni distincte de cod n paralel n interiorul
aceluiai proces. Cteodata ns, aceste portiuni de cod care constituie corpul threadurilor, nu
sunt complet independente i n anumite momente ale execu iei, se poate ntampla ca un thread
s trebuiasc s atepte execuia unor instructiuni din alt thread, pentru a putea continua execu ia
propriilor instruciuni. Aceast tehnic prin care un thread asteapt execu ia altor threaduri nainte
de a continua propria execuie, se numete sincronizarea threadurilor.
Att firele de execuie, ct i procesele au stri ce pot fi sincronizatepentru a evita problemele ce
pot aprea datorita faptului c mpart diverse resurse . n general, fiecare fir de execuie are o
sarcin specific i este programat astfel nct s optimizeze utilizarea procesorului.
Strile unui fir de execuie[modificare | modificare surs]
Principalele stri ale unui fir de execuie sunt: Activ, Pregtit i Blocat. Comparativ cu
acestea, procesele au i starea specific Repaus (Sleep). Daca un proces este eliminat din
memoria RAM, toate firele de execuie ale acestuia vor fi oprite, deoarece se aflau n aceli
spaiu de memorie ca i procesul respectiv.
Schimbarea unei stri[modificare | modificare surs]

Crearea: Atunci cnd un proces este pornit, se creeaz un thread pentru acel proces. Apoi,
acel thread poate crea i gestiona mai multe threaduri, fiecare avnd pointeri ctre
instruciunile specifice lui.

Blocarea: Atunci cnd un thread trebuie s atepte altul, acesta este blocat - fiind salvat n
stiv pointerul la acesta. Funcia de blocare se poate apela att din interiorul ct i din
exteriorul threadului.

Deblocarea: Un thread blocat poate fi deblocat n urma unei comenzi externe.

La alegere, n locul blocrii/deblocrii threadurilor, acestea pot primi prioriti de execuie, ns


aceast metod este mai ineficient, deoarece procesorul tot va comuta de la un thread la altul,
operaie ce va ocupa cicli de procesor. Cu varianta din urma nsa, se vor evita mai uor erori de
programare prin care doua sau mai threaduri se vor atepta ntre ele, blocnd un proces ntreg
(deadlock).

Finalizarea: Atunci cnd un thread este finalizat, se va elibera memoria alocat acestuia.

HTTP sau HyperText Transfer Protocol este un protocol de comunicaie tip cerere/rspuns ntre un client
web i un server. Clientul este reprezentat de ctre navigatorul web folosit de un utilizator pentru a accesa i
afia coninutul web dintr-o reea sau de pe Internet.

Clientul trimite o cerere ctre un server care gzduiete coninut web, care va rspunde clientului prin
trimiterea coninutului spre afiare ctre client. Rspunsul server-ului reprezint confirmarea c acesta a
primit cu succes solicitarea clientului i i poate rspunde conform cererii acestuia.

Aadar, HTTP poate fi considerat o regul pentru ca un utilizator s poat accesa site-uri web. De asemenea,
nu exist legtur ntre dou comenzi HTTP consecutive diferite. n plus, n protocol exist implementat i
o list de coduri de stare, folosite de un server pentru notificarea unui navigator web n cazul unei probleme.
De exemplu, 404 Not Found este folosit pentru a informa un utilizator c pagina accesat de acesta nu
exist la adres.
HTTP folosete protocolul TCP (Transmission Control Protocol) pe portul 80 pentru a trimite i primi
pachete de date ntr-o reea. Astfel, putem accesa i dispune de aplicaii web precum email, World Wide
Web, transfer de fiiere, etc. ns, protocolul HTTP se folosete i de protocolul UDP (User Datagram
Protocol) care este un protocol nesigur.
Metode
Metodele disponibile sunt :
GET: este cea mai folosit metod, fiind utilizat atunci cnd serverului i se cere o resurs.
HEAD: se comport exact ca metoda GET, dar serverul returneaz doar antetul resursei, ceea ce permite
clientului s inspecteze antetul resursei, fr a fi nevoit s obin i corpul resursei.
PUT: metoda este folosit pentru a depune documente pe server, fiind inversul metodei GET.
POST: a fost proiectat pentru a trimite date de intrare ctre server.
DELETE: este opusul metodei PUT.
TRACE: este o metod folosit de obicei pentru diagnosticare, putnd da mai multe informaii despre traseul
urmat de legtura HTTP, fiecare server proxy adugndu-i semntura n antetul Via.
OPTIONS: este folosit pentru identificarea capacitilor serverului Web, nainte de a face o cerere.
CONNECT: este o metod folosit n general de serverele intermediare.
XPath (XML Path Language) este un limbaj de expresii utilizat pentru a selecta poriuni dintr-un
document XML sau pentru a calcula valori (iruri de caractere, numere, sau valori buleene) pe
baza coninutului unui document XML. Versiunea actual a limbajului este XPath 2.0, dar cea mai
ntlnit versiune n prezent este versiunea 1.0.
Limbajul XPath este structurat pe reprezentarea sub form de arbore a documentului XML, oferind
posibilitatea de a naviga n acest arbore, prin selecia nodurilor XML care satisfac diferite criterii.
n utilizarea frecvent (care nu este o specificaie oficial), o expresie XPath este deseori
numit un XPath.
Motivaia apariiei acestui limbaj a fost dorina de a folosi aceeai sintax i acelai model
att pentru XPointer ca i pentruXSLT, XPath s-a ncetenit printre programatori ca fiind un mic
limbaj de interogare, iar anumite pri ale sale sunt folosite n specificaiile W3C pentru XML
Schema i XForms.
Notaie[modificare | modificare surs]

Cea mai ntlnit metod a expresiilor XPath (cea de la care provine i numele limbajului) este path
expression. Un path expression este scris ca o secven de pai pentru a ajunge dintr-un nod XML ('context
node'-ul curent) la un alt nod sau un alt set de noduri. Paii sunt separai de caracterul "/" (ex. path). Fiecare
pas are trei componente:
Specificatorul de axe
Node Test
Predicat
Exist dou notaii - prima, cunoscut ca sintaxa abreviat, este mai compact i permite ca XPath-urile sa
fie scrise i citite ntr-un mod mai intuitiv, i n multe cazuri, seturi de caractere i construc ii mai intuitive.
Sintaxa complet este mai complex, dar permite specificarea mai multor opiuni, i descrierea mai detaliat
- n cazul n care se citete cu mai mult atenie.
Sintaxa abreviat[modificare | modificare surs]
Notarea compact permite mai multe notaii implicite i abrevieri pentru cazurile cele mai comune. Cel mai
simplu XPath are urmtoarea form
/A/B/C
prin care se selecteaz elementele C care sunt copii elementelor B, care la rndul lor sunt copii elementelor
A, care este cel mai cuprinztor element al documentului XML. Sintaxa XPath s-a fcut pentru a simula
sintaxa URI (Uniform Resource Identifier) i sintaxa cilor spre fiiere.
Expresii mai complicate pot fi construite prin specificarea unei axe diferite de axa 'copil' implicit, un nod
test diferit de un simplu nume, sau predicate, care sunt scrise ntre paranteze ptrate pentru fiecare pas. De
exemplu, expresia

A//B/*[1]
selecteaz primul element ('[1]'), oricare ar fi numele lui ('*'), care este copilul ('/') unui nod B, care la rndul
su este copilul unui descendent mai cuprinztor ('//') al unui element A, care este copilul nodului contextual
curent (expresia nu ncepe cu '/'). Merit notat c dac exist mai multe elemente B corespunztoare n
document, se va returna un set ntreg de primi copii.

Sintaxa extins[modificare | modificare surs]


Folsind sintaxa extins, cele dou exemple s-ar fi scris

/child::A/child::B/child::C
child::A/descendant-or-self::node()/child::B/child::*[position()=1]
n acest exemplu, la fiecare pas al XPath-ului, axa (e.g. child sau descendant-or-self) este specificat n mod
explicit, fiind urmat de :: i mai apoi de node test, precum A sau node() din exemplul de mai sus.

Anda mungkin juga menyukai