UF1: Programació amb XML

Resultats d'aprenentatge:

  1. Reconeix les característiques de llenguatges de marques analitzant-ne i interpretant-ne fragments de codi.
  2. Utilitza llenguatges de marques per a la transmissió d’informació a través del web analitzant l’estructura dels documents i identificant-ne els elements.
  3. Estableix mecanismes de validació per a documents XML utilitzant mètodes per definir-ne la sintaxi i l’estructura.

Introducció als llenguatges de marques

Dades

Tenim dades que s'han de emmagatzemar o transmetre. Les podem tenir:

  • En paper.
  • En memòria (volàtil).
  • Fitxers senzills, com ara un full de càlcul.
  • Emmagatzemament distribuït de dades.
  • Correu electrònic (client i servidor).
  • Servei de directori: DNS, LDAP, etc.
  • Bases de dades: relacionals, orientades a objecte, NoSQL, etc.

L'elecció dependrà de l'estructura i l'accés que requereixen les dades. Per exemple: els fitxers són molt senzills d'implementar, però si hi ha moltes dades relacionades entre sí, potser una base de dades és millor opció.

Fitxers

La serialització és el procés de salvar un objecte a un medi d'emmagatzematge (com pot ser un fitxer, o un buffer de memòria) amb la finalitat de transmetre'l a través d'una connexió en xarxa com una sèrie de bytes o en un format humanament més llegible, com per exemple XML. La sèrie de bytes o el format es poden utilitzar per recrear un objecte que és idèntic en el seu estat intern a l'objecte original. Aquest tipus de serialització s'utilitza principalment:

  • Per transportar un objecte a través d'una xarxa,
  • per persistir objectes a un fitxer o base de dades, o
  • per a distribuir objectes idèntics a unes quantes aplicacions o localitzacions.

El format de les dades pot ser propietari o obert. Si treballem a un sol domini, podem utilitzar qualsevol dels dos formats. Alguns formats oberts són RDF, XML, Atom (dialecte de XML), JSON o YAML.

Els formats propietaris són molt nombrosos. Alguns estan documentats, i altres no. Alguns han variat el seu estatus al llarg del temps: DOC (Office) era tancat i no documentat, però Microsoft el va obrir al 2006.

Format text

Un arxiu de text pot codificar-se de diferents formes. La més habitual és el conjunt ASCII. Però això limita el nombre de caràcters a 128. El format més estès que soporta la majoria de caràcters d'escriptura és UTF-8.

El format de fi de línia és diferent per cada sistema operatiu: Windows (CR + LF), Unix/Linux (LF) i macOS (CR).

Veure la referència de Unicode (UTF-8).

Format binari

El format binari és una altra forma de dir als fitxers no de text. La seva estructura sol ser propietària, amb seqüencies de bytes. Solen tenir una capçalera que permet identificar-los, així com metadades per indicar les característiques del seu contingut. Exemples: arxius de vídeo i àudio, executables.

Llenguatge de marques (Markup)

Un llenguatge de marques és un sistema per marcar o etiquetar un document de text per tal d'explicar la seva estructura lògica.

Característiques:

  • El marcat hauria de ser declaratiu: hauria de descriure l'estructura d'un document i altres atributs, en lloc d'especificar el processament que es realitzarà en ell. El marcat declarat és menys probable que entri en conflicte amb les necessitats i les tècniques futures de processament imprevistes.
  • El marcat ha de ser rigorós perquè les tècniques disponibles per processar objectes definits amb rigor, com ara programes i bases de dades, també es poden utilitzar per processar documents.

Tipus de llenguatges de marques:

  • De presentació: inclouen marques dins del text per indicar les entitats que conté: títols, paràgrafs, pàgines, etc. Exemples: HTML, Wikitext.
  • Procedimentals: també orientats a la presentació, però consisteix en comandes per formatejar el text. S'utilitza a sistemes batch, com Tex.
  • Descriptiu: el llenguatge no et diu què fer, sinó què és, mitjançant etiquetes. El exemple principal és XML.

HTML5 ha fet un intent de ser més descriptiu (semàntic) traient la part de presentació a CSS.

Llenguatge de marques extensible (XML)

El llenguatge de marcatge extensible (XML) és un llenguatge de marques que defineix un conjunt de normes per a la codificació de documents en un format que sigui llegible per humans i que es pugui llegir amb màquina.

Com podem fer que una màquina o aplicació escrigui dades i altra les pugui llegir?

  • Utilitzant un format de dades fàcil de llegir: text, definint la codificació que s'utilitzarà (UTF8, UTF16, etc.).
  • Amb un manual de referència compartit que descrigui el procés.

Documents XML

  • When do I use elements and when do I use attributes for presenting bits of information?
  • When do I require an order for elements, and when do I just allow arbitrary order?
  • When do I use wrapper elements around sequences of similar elements?

For the first question:

  • If the information in question could be itself marked up with elements, put it in an element.
  • If the information is suitable for attribute form, but could end up as multiple attributes of the same name on the same element, use child elements instead.
  • If the information is required to be in a standard DTD-like attribute type such as ID, IDREF, or ENTITY, use an attribute.
  • If the information should not be normalized for white space, use elements.

Principles to follow:

  • Core content: If you consider the information in question to be part of the essential material that is being expressed or communicated in the XML, put it in an element. If you consider the information to be peripheral or incidental to the main communication, or purely intended to help applications process the main communication, use attributes.
  • Structured information: If the information is expressed in a structured form, especially if the structure may be extensible, use elements. If the information is expressed as an atomic token, use attributes.
  • Readability: If the information is intended to be read and understood by a person, use elements. If the information is most readily understood and digested by a machine, use attributes.
  • Element/attribute binding: Use an element if you need its value to be modified by another attribute.

Namespaces

XML namespaces provide a way to distinguish duplicate element and attribute names. Duplicates element and attribute names can occur when an XML document contains elements and attributes from two or more different XML schemas (or DTDs). To quote Wikipedia: "In general, a namespace is an abstract container providing context for the items ... it holds and allows disambiguation of items having the same name."

An XML namespace is identified by an unique name (called a URI, not a URL, even though it can look like a URL). An URI is any string, although most people choose a URL-based URI because URLs are an easy way to hope for uniqueness. Although there's nothing preventing someone else from using the namespace http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul, it's fairly unlikely anyone would choose that accidentally. Even if they did accidentally choose it, they may not define the same elements as XUL anyway (e.g., <textbox/>) in their schema/DTD.

Any element type or attribute name in an XML namespace can be uniquely identified by its XML namespace and its "local name". Together, these two items define a qualified name, or QName.

For example, <xul:textbox/> uses a namespace named "xul" and a local name "textbox". This distinguishes it from, for example, <foobar:textbox/> which might occur in the same document. The xul and foobar namespaces must be defined at the top of the XML document in which they are used, like so:

<foobar:some-element 
     xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
     xmlns:foobar="the-foobar-namespace">
   <xul:textbox id="foo" value="bar"/>
   <foobar:textbox favorite-food="pancakes"/>
 </foobar:some-element>

Notice I've mixed two <textboxes/> in the same document. The only way to distinguish that they have different meanings is with namespaces.

There's only one other thing to know: "default namespace". Every XML element has a "default namespace", and this is used with XUL elements all the time. In XUL documents, you'll usually see this:

<window
     id="foo"
     xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
   ...
   ...
 </window>

and in XHTML documents, you'll see this:

<html xmlns="http://www.w3.org/1999/xhtml">
   ...
   ...
 </html>

There is a very subtle difference here than before. Before I wrote xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" but here the :xul piece is omitted. This signifies to the XML parser that http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul is the default namespace for the element and its descendant elements (unless further overridden by a default namespace on a descendant element), and that any element without a namespace (i.e., no prefix and colon) belongs to the default namespace. That's why we can write the shorthand <textbox/> instead of <xul:textbox/> in XUL (although the latter is just as correct when not using http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul as the default namespace) -- the XUL namespace is defined as the default on the topmost element. In other words, a default namespace permits a kind of short-hand to be used for all descendants of an element.

Validació DTD

Veure el aquest i aquest tutorial.

XML Schema

Veure també aquest contingut de IOC.