Manual del Desarrollador de XMLEye

Antonio García Domínguez

Universidad de Cádiz


    
  

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License”.


Tabla de contenidos

1. Compilación del código fuente
XMLEye: visor XML genérico
ACL2::Procesador: módulo y guión Perl
2. Creación de tipos de documentos
Introducción
Creación de un convertidor
Creación de un descriptor de tipo
3. Creación de hojas de usuario
Introducción
Diseño del sistema de hojas de usuario
Localización de una hoja de usuario
Herencia a partir de un tipo base
Hojas de preprocesado: particularidades
Hojas de visualización: particularidades
Bibliografía
A. GNU Free Documentation License

Capítulo 1. Compilación del código fuente

Una nota: aunque hay instantáneas disponibles del código fuente, éstas son más para los usuarios que los desarrolladores. En caso de querer participar como desarrollador, recomiendo encarecidamente usar una copia de trabajo del repositorio Subversion. Bastará con instalar el paquete subversion y seguir algunas instrucciones sencillas. Para más información, véase el excelente libro [1].

XMLEye: visor XML genérico

Antes de nada, necesitaremos un JDK que implemente J2SE 6.0 o superior, como IcedTea, la herramienta de construcción Ant, y el entorno de pruebas de unidad JUnit (ha de ser una versión 3.X, o no funcionará):

sudo aptitude install icedtea-java7-jdk ant junit

Ahora tendremos que crear una copia de trabajo local de la última revisión de la rama principal de desarrollo del repositorio de Rediris:

svn checkout https://forja.rediris.es/svn/csl2-xmleye/XMLEye/trunk xmleye

Ya podemos introducirnos en xmleye y aprovechar los objetivos ya definidos en el fichero build.xml de Ant: compilar todo el código y ejecutar

clean

Limpia el árbol de directorios existente.

compile

Compila todo el código fuente.

dist

Compila las fuentes ,ejecuta las pruebas de unidad y genera una distribución autocontenida en el subdirectorio dist.

dist-jar

Tras compilar y ejecutar las pruebas de unidad, genera un fichero .jar bajo dist, pero no llega a empaquetarlo con todo lo demás.

docs

Genera la documentación del API en formato HTML en el subdirectorio docs a través de Javadoc.

run

Se trata del objetivo por defecto (ejecutado a través de ant). Compila el código y ejecuta la versión así compilada de XMLEye.

run-about

Compila el código y ejecuta únicamente la ventana de "Acerca de". Útil a la hora de diseñar la interfaz.

run-find

Como la anterior, pero para el diálogo de búsqueda.

run-types

Más de lo mismo, pero para el diálogo de edición de tipos.

test

Ejecuta las pruebas de unidad. La salida de cada conjunto de pruebas se halla bajo el fichero TEST-* correspondiente.

Un par de notas adicionales: esta aplicación depende de InfoNode Tabbed Panel 1.5.0 (licenciado bajo la GPL para uso no comercial) y del look and feel JGoodies Looks 2.1.4 (licenciado bajo BSD), disponibles en http://www.infonode.net/index.html?itp y https://looks.dev.java.net/ respectivamente. De todas formas, los ficheros .jar necesarios se hallan en el propio repositorio, por lo que no hay que hacer nada al respecto.

Además, el desarrollo puede hacerse mucho más cómodamente si se emplea el plugin Subclipse para Eclipse, disponible en http://subclipse.tigris.org/, y se importa a través de él el proyecto Eclipse desde el repositorio. Así podemos contar con sus funcionalidades de refactorización y notificación de errores y avisos de compilación en directo.

ACL2::Procesador: módulo y guión Perl

Este módulo se halla escrito usando las prácticas habituales de diseño de paquetes de Perl, por lo que no sorprenderá a nadie con cierta experiencia en la materia. Por supuesto, necesitaremos Perl, y además unos cuantos más paquetes del CPAN. También necesitaremos el paquete de la biblioteca de análisis de XML de GNOME, LibXML:

sudo aptitude install perl libxml2-dev

Otra opción, si hemos habilitado los repositorios de XMLEye y compañía, es aprovechar la información disponible en el paquete fuente de ACL2::Procesador, libacl2-procesador-perl:

sudo apt-get build-dep libacl2-procesador-perl

A continuación obtendremos una copia local de trabajo del repositorio:

svn checkout https://forja.rediris.es/svn/csl2-xmleye/pprocACL2/trunk pprocACL2

Nos introducimos en dicho directorio y aprovechamos el Makefile.PL para crear el Makefile con el que trabajaremos, y asegurarnos de que tenemos todas las dependencias:

cd pprocACL2
sudo perl Makefile.PL
sudo chown -R `id -un`.`id -gn` *

La segunda orden era para devolver todos los ficheros creados con permisos de superusuario por el Makefile.PL a nosotros. La primera orden usó sudo ya que podría tener que instalar módulos del CPAN en nuestro sistema (no debería de tener por qué si usamos los paquetes de desarrollo de XMLEye).

Ya podemos compilar con make y lanzar las pruebas de regresión con make test.

Capítulo 2. Creación de tipos de documentos

Introducción

XMLEye, como el nombre indica, se trata de un visor genérico de documentos XML. Pero ello no lo limita a únicamente ficheros XML: si se le proporciona la información necesaria acerca de cómo distinguir un cierto tipo de fichero, y cómo convertirlo a formato XML, podrá abrirlo de forma transparente tal y como abre un fichero XML.

La información referente a cómo identificar y, opcionalmente, qué hacer para convertir un formato determinado se halla en un descriptor de tipo. Este descriptor puede incluir una referencia a cualquier ejecutable que haga las veces de convertidor a un documento XML.

En este capítulo veremos qué condiciones debe cumplir un convertidor, y cómo habría que escribir posteriormente el descriptor para integrarlo con XMLEye. En cuanto a su instalación, véase el Manual de Usuario: realmente es tan sencillo como asegurar que el convertidor esté bajo la ruta correcta y copiar el descriptor de tipos a su sitio.

Creación de un convertidor

Un convertidor puede ser cualquier cosa que podamos ejecutar: desde un programa en código máquina hasta guiones Perl o Python. Yo en particular prefiero usar Perl, ya que se halla mejor ajustado a la tarea de procesar texto, pero cualquier cosa sirve.

Salvado el tema del lenguaje, las restricciones que ha de cumplir nuestro convertidor son:

  1. Debe de poder aceptar a través de la línea de órdenes la ruta absoluta del fichero a convertir.

  2. Debe de ofrecer el resultado a través de la salida estándar, e imprimir errores por la salida estándar de errores.

  3. Ha de comportarse como cualquier ejecutable tipo UNIX, devolviendo el código de estado 0 en caso de éxito y distinto de cero en caso de error.

  4. Ha de instalarse dentro de alguno de los directorios en el PATH del usuario que vaya a ejecutar XMLEye. Puede ser algún directorio común a todos los usuarios, como /usr/bin o /usr/local/bin, o puede ser específico a un usuario.

Sería recomendable que además contara con su propia ayuda, en caso de aceptar más opciones, y su página man, pero no es imprescindible.

Un ejemplo muy simple de qué podría hacerse puede extraerse del guión yaml2xml del módulo YAXML::Reverse:

#!/usr/bin/perl

use strict;
use warnings;
use YAXML::Reverse qw(ConvertFile);

# Argument processing
if (scalar @ARGV != 1) {
    print "Usage: $0 [path to .yaml]\n";
    exit 1;
}
my ($path) = @ARGV;

# Convert the YAML file
print ConvertFile($path);
exit 0;

Como puede verse, no es más que un guión Perl normal y corriente: la primera línea indica con qué intérprete debería ejecutarse al intentar ejecutarse. Es decir, si intentamos hacer esto:

./yaml2xml

, realmente haremos esto:

/usr/bin/perl ./yaml2xml

A continuación activamos las opciones habituales de comprobación de errores de Perl strict y warnings, e importamos la función ConvertFile del módulo YAXML::Reverse, que implementa realmente toda la funcionalidad.

Ofreciendo esta funcionalidad separada en un módulo aparte nos aseguramos de que pueda ser reutilizada en un futuro a través de otros medios.

A continuación procesamos los argumentos, recibiendo la ruta absoluta al fichero .yaml que antes mencionamos, y mostrando un mensaje de uso (junto con el código de estado correspondiente) si no se ha proporcionado.

Por último imprimimos el resultado de la conversión por la salida estándar e indicamos mediante el código de estado 0 que todo ha ido bien.

Creación de un descriptor de tipo

Para decirle a XMLEye que acepte un nuevo tipo de fichero, y que se integre con un determinado editor y convertidor, todo lo que hemos de hacer es escribir un corto fichero XML como el siguiente:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE type SYSTEM "accepted-doc.dtd">
<type xmlns="http://xmleye.uca.es/xmleye/accepted-doc">
  <name>Fichero YAML/JSON</name>
  <name language="en">YAML/JSON file</name>
  <edit_cmd>emacs %s</edit_cmd>
  <import_cmd>yaml2xml %s</import_cmd>
  <extensions>
    <extension>yaml</extension>
    <extension>yml</extension>
    <extension>json</extension>
  </extensions>
</type>

Yendo línea a línea por el fichero anterior, nos encontramos con lo siguiente:

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

Se trata de la declaración que todo fichero XML debiera (aunque no tiene por qué) incluir. Indica que estamos empleando la versión 1.0 del estándar: aunque también existe la versión 1.1, las diferencias no nos importan en este caso.

<!DOCTYPE type SYSTEM "accepted-doc.dtd">

Esta línea indica al analizador XML de XMLEye cómo puede validar el documento. El fichero accepted-doc.dtd es parte de XMLEye y se halla preinstalado junto con el descriptor de tipo de documento XML, xml.type.

<type xmlns="http://xmleye.uca.es/xmleye/accepted-doc">
...
</type>

El descriptor de documento viene representado globalmente por un elemento de nombre type y del espacio de nombres de descriptores de tipos de XMLEye.

<name>Fichero YAML/JSON</name>
<name language="en">YAML/JSON file</name>

Estas dos líneas indican el nombre del tipo de documento que se le mostrará al usuario. Un detalle importante es el atributo language: esto nos permite localizar la misma descripción a distintos idiomas e incluso dialectos, si así lo deseamos. El algoritmo de búsqueda es bastante sencillo:

  1. Sea P el código del país (según el estándar ISO-3166) de la localización del usuario, detectada a partir de los ajustes de su sistema operativo, y L el código de idioma, según el estándar ISO 639.

  2. Se busca una entrada cuyo atributo language tenga la forma 'L_P', coincidiendo tanto el país como el lenguaje. Esto nos permite, por ejemplo, usar distintas entradas para inglés americano e inglés británico.

  3. A continuación se busca solamente por el idioma ('L').

  4. Si aun así no hemos conseguido nada, tomaremos el nombre por defecto (aquel sin atributo language).

<edit_cmd>emacs %s</edit_cmd>
<import_cmd>yaml2xml %s</import_cmd>

Éstas son las órdenes que XMLEye debe de usar para editar el fichero original (y no el fichero XML resultado de la conversión), y para convertir el fichero a XML. De hecho, XMLEye invocará al convertidor cada vez que considere que ha habido cambios en el fichero original, si se ha activado la opción Actualización Automática.

<extensions>
  <extension>yaml</extension>
  <extension>yml</extension>
  <extension>json</extension>
</extensions>

Por último, el elemento extensiones incluye una serie de subelementos extension que relacionan ciertas extensiones de fichero con el tipo de documento en cuestión. En otros estándares parecidos como la especificación de shared-mime-info de Freedesktop.org ([2]) implementan también un sistema basado en el contenido del fichero, pero por simplicidad no lo he considerado.

Capítulo 3. Creación de hojas de usuario

Introducción

A través de los tipos de documento, XMLEye puede efectivamente abrir cualquier tipo de fichero para el que podamos imaginarnos una conversión a XML. Con ello ya disponemos no de un visor genérico de XML, sino de un visor genérico en XML.

Sin embargo, no sería tan interesante si sólo pudiéramos ver el resultado de la conversión tal y como queda: es posible que queramos poner icono o una etiqueta amigable a algunos nodos, ocultar otros, añadir nuevos nodos, o simplemente reorganizarlos. Éstas son las tareas de cualquier hoja de preprocesado.

Incluso así, seguimos teniendo un árbol XML normal y corriente. ¿Y si quisiéramos ver en detalle toda la información concerniente a un nodo determinado, con hipervínculos a todo aquello que nos pueda ser de interés? Ahí es donde entran en juego las hojas de visualización, que crean esos resúmenes en formato XHTML para cada nodo del árbol que sea visible al usuario.

En esencia, estas hojas son ficheros XSLT (eXtensible Stylesheet Transformations), sobre los cuales XMLEye implementa una serie de extensiones, permitiendo su fácil localización y reutilización. Varios ficheros XSLT pueden reunirse en un único ente coherente, que aquí llamaremos hoja de usuario.

Para aquellos a los que les preocupe el rendimiento: estas hojas son compiladas a bytecode Java en su primera ejecución, siendo mucho más rápidas en las posteriores transformaciones. Dicha representación se conoce en Xalan con el nombre de translets. De hecho, si quisiéramos, podríamos generar versiones empaquetadas de esas hojas y usarlas dentro de la línea de órdenes.

Diseño del sistema de hojas de usuario

Todas las hojas de usuario empleables por XMLEye se hallan instaladas en lo que llamaremos un repositorio de hojas de usuario. Normalmente este repositorio se halla bajo el subdirectorio xslt de donde esté xmleye.jar, o en su defecto en el directorio desde el cual se lance XMLEye: en el paquete Debian se trata de /usr/share/xmleye, por ejemplo.

Mirando en su interior, veremos tres ficheros XSLT:

preproc.xsl

Por sencillo que parezca, éste es el punto de entrada a partir del cual siempre se comienza toda transformación de preprocesado. Además de importar la hoja util.xsl y definir variables con rutas a iconos predefinidos, se importa una hoja llamada current_preproc.

Tal hoja no existe en ninguna parte: de hecho, se trata de una de las extensiones propias de XMLEye. Es una URI especial que se resuelve a la ruta de la hoja de preprocesado seleccionada automáticamente por el usuario. Bueno, casi, pero ya lo veremos después.

view.xsl

De forma análoga al caso anterior, éste es el punto de entrada para toda visualización en formato XHTML. Además de importar la hoja de utilidades y la hoja de visualización elegida por el usuario, activa el modo de salida en XHTML y, lo que es más importante, inicia la transformación por el nodo que haya seleccionado el usuario (proporcionado mediante el parámetro selectedUID).

¿Y de dónde viene este UID? Pues del preprocesado, precisamente. Es una de las pocas cosas que absolutamente toda hoja de preprocesado debe hacer. De todas formas, si hacemos que nuestra hoja de preprocesado herede de la hoja base xml, no tendremos que preocuparnos por esto.

Un detalle importante: se puede imaginar uno fácilmente que buscar por todo el documento el nodo que tenga un determinado identificador tiene que ser bastante costoso, y de hecho, lo es. Por ello, esta hoja crea un índice a nivel del documento completo de todos los identificadores y sus nodos correspondientes, con lo que la búsqueda posterior a la primera será mucho más rápida.

util.xsl

Esta hoja ya no cumple un papel tan importante: simplemente define algunas funciones de utilidad para la manipulación de cadenas, como util:to-lower (cambio a minúsculas), util:to-upper (cambio a mayúsculas) o util:substring-after-last (que toma la subcadena posterior a la última aparición de la clave, y de lo contrario la cadena completa).

En un futuro puede que estas funciones se hagan redundantes si realizo el cambio a XSLT 2.0, pero las dejaré ahí de todas formas, ya que no creo que hagan daño.

Las hojas de usuario son subdirectorios de view (para las hojas de visualización) y preproc (para las de preprocesado), y aparecerán bajo XMLEye con el mismo nombre que tenga el subdirectorio.

Toda hoja de usuario tendrá como mínimo un fichero XSLT, pero puede tener varios. De hecho, en el siguiente capítulo veremos por qué nos interesaría hacerlo así.

Localización de una hoja de usuario

Una preocupación constante durante el diseño de XMLEye ha sido su internacionalización, es decir, la implantación de la infraestructura necesaria para poder localizarlo a distintos lenguajes, atendiendo incluso a la presencia de dialectos distintos entre países.

Las hojas de usuario generan contenidos que el usuario podrá ver, así que no son ninguna excepción. Pero, ¿cómo podemos localizarlas entonces?

La idea es realmente muy simple: antes vimos que las hojas de preprocesado o de visualización en general tienen un punto de entrada bien definido: preproc.xsl y view.xsl, respectivamente.

Bien, pues lo mismo ocurre con el interior de toda hoja de usuario. Si recordamos la forma en que se buscaba el nombre de un tipo de documento determinado, el método es muy similar. Sea L el código de idioma de la localización actual según ISO 639 y P el código de país según ISO 3166. Si el usuario ha seleccionado actualmente la hoja H de usuario de preprocesado, se intentará resolver la URI current_preproc a uno de estos ficheros XSLT, en el mismo orden:

  1. xslt/preproc/H/H_L_P.xsl

  2. xslt/preproc/H/H_L.xsl

  3. xslt/preproc/H/H.xsl

Una consecuencia de este esquema es que si vamos a presentar varias traducciones del texto generado, no deberíamos repetir la funcionalidad de la hoja varias veces, sino dividirla en dos partes:

  1. El punto de entrada antes mencionado definirá una serie de variables y/o plantillas con nombre para localizar el texto generado, e importará a la hoja principal que proporcione la verdadera funcionalidad.

  2. La hoja principal con toda la funcionalidad no generará texto por su cuenta, sino que quedará completamente dependiente de las variables de la hoja que actúe de punto de entrada.

Esto le resultará muy familiar a cualquiera que haya trabajado con gettext, por ejemplo: por un lado tenemos el diccionario de cadenas, y por otra el código propiamente dicho.

Este es el enfoque que se ha seguido en la hoja de visualización por defecto, xml, por ejemplo: se tiene el fichero xml.xsl, que actúa como punto de entrada por defecto en español, y principal.xsl, que realmente implementa la funcionalidad necesaria.

Nota

A la hora de importar ficheros XSLT concretos, hay que emplear la ruta relativa completa a partir del directorio xslt: así, cuando xml.xsl importa a principal.xsl, ha de emplear la ruta relativa completa, aunque se halle en el mismo directorio:

<xsl:import href="view/xml/principal.xsl"/>

Herencia a partir de un tipo base

El propio estándar XSLT ya define mecanismos para la herencia: a través del elemento xsl:import podemos importar todas las reglas de otro fichero XSLT, con menos precedencia que las actuales, de tal forma que podamos efectivamente especializar dicha hoja, redefiniendo y ampliando ciertos aspectos de forma parecida a la herencia del mundo orientado a objetos.

Sin embargo, no se debe usar directamente de esa forma: el estándar sólo hace referencia a URL estáticas, con lo que perderíamos la capacidad de emplear la infraestructura de internacionalización que antes mencionamos.

Para poder seguir usando el esquema de resolución dinámica de puntos de entrada para la hoja que vayamos a especializar, tendremos que seguir usando URI especiales. En particular, URI de la forma view_X se resuelven al punto de entrada correcto de la hoja X de usuario de visualización. Las URI de la forma preproc_X son sus análogas para las hojas de preprocesado.

La hoja de preprocesado para ACL2, ppACL2, especializa la hoja de preprocesado xml así:

<xsl:import href="preproc_xml"/>

Resulta interesante mencionar que la especialización se puede hacer a muchos niveles, como de costumbre. Así, summaries y reverse son a su vez especializaciones de ppACL2.

Hojas de preprocesado: particularidades

Ya hemos comentado anteriormente que la principal responsabilidad de toda hoja de preprocesado era añadir el atributo UID con identificadores únicos para cada nodo del árbol, para que el usuario pudiera así seleccionarlo y conseguir una visualización en formato XHTML de su contenido relevante.

También comentamos que escribiendo nuestra hoja de preprocesado como una especialización de la hoja xml no tendríamos que preocuparnos de ello. Sin embargo, hemos de tener en cuenta un poco el diseño de esta hoja para ver cómo se usa.

En cuanto arranca, esta hoja cambia al modo process-node, en el cual dispone de una regla por defecto para todo elemento que:

  1. Crea una copia del elemento actual, junto con sus atributos.

  2. Añade el atributo UID con el identificador único del elemento.

  3. Invoca las plantillas del usuario sobre el nodo actual, para que añada nuevos atributos, elementos o en general lo que quiera. La única condición es que sean parte del modo por defecto de XSLT (es decir, carezcan de atributo mode). Por defecto no hace nada.

  4. Copia todos los hijos de tipo texto.

  5. Invoca otra vez plantillas del usuario, esta vez bajo el para determinar qué hijos se procesarán a continuación, y en qué orden. Por defecto continúa en el mismo orden, por todos los hijos del nodo actual.

Como vemos, esta hoja sigue el patrón de diseño Método Plantilla, en una versión del principio de Hollywood: "No nos llames; nosotros te llamaremos". Cualquier hoja que especialice a ésta debe únicamente de definir las plantillas del modo por defecto y modo process-children como lo vea conveniente para modificar y expandir su comportamiento.

Ahora que sabemos cómo añadir nuevos atributos, elementos, o incluso cómo quitarlos (no recorriéndolos bajo el modo process-children), podemos pasar a hablar de una serie de atributos especiales que nos permiten hacer cosas sobre cómo ve el usuario nuestro documento:

hidden

Si este atributo se pone a "1", el elemento no será visible por el usuario.

leaf

Si este atributo se pone a "1", el elemento será considerado como hoja, y sus hijos no serán visibles al usuario.

Un ejemplo, extraído de la hoja de visualización de YAML, que oculta todos los nodos con nombre _key:

<!-- Hide all yaml:_key elements -->
<xsl:template match="*[local-name(.)='_key']">
  <xsl:attribute name="hidden">1</xsl:attribute>
</xsl:template>
nodeicon

Contiene la ruta relativa a partir del mismo directorio donde se halla el repositorio de hojas de usuario (es decir, el directorio xslt) al icono de 16x16 píxeles que se desee mostrar para dicho nodo.

La hoja de visualización de demostraciones de ACL2 usa esto para mostrar de forma sencilla qué elementos han tenido éxito en su demostración y en cuáles no.

nodelabel

Contiene la etiqueta a usar para el nodo en cuestión. Esto permite levantar así algunas restricciones típicas sobre los árboles XML normales, en los cuales los nombres de elementos no pueden tener espacios o ciertos carácteres.

La hoja de visualización de ficheros YAML/JSON usa este atributo para poner etiquetas en los pares clave/valor de los mapas: YAML es más permisivo en las claves de los mapas que XML, permitiendo espacios, por ejemplo.

<!-- Label map values using their keys -->
<xsl:template match="*[local-name(.)='_value']">
  <xsl:attribute name="nodelabel">
    <xsl:value-of select="preceding-sibling::*[local-name(.)='_key'][1]"/>
  </xsl:attribute>
</xsl:template>

Hojas de visualización: particularidades

A la hora de elaborar una hoja de visualización, hemos de tener en cuenta dos cosas. En primer lugar, normalmente especializaremos la hoja xml, consiguiendo así ciertas facilidades, como la plantilla skeleton, a la cual le pasaremos el argumento rtf (Result Tree Fragment) con el código XHTML que queramos que aparezca dentro del cuerpo del documento.

Este esqueleto, por defecto, generará enlaces a todos los antecesores del nodo actual antes del cuerpo, y a todos los hijos inmediatos después del cuerpo.

Por defecto, la hoja de visualización de xml mostrará todos los atributos y nodos texto hijos del nodo actual. En este caso no hay tantos requisitos sobre la estructura de la hoja de visualización como antes. De hecho, podemos ignorar por completo la plantilla de generación del esqueleto y usar el nuestro.

Sin embargo, una cosa que sí es importante es la generación de hipervínculos entre distintos nodos. XMLEye añade la funcionalidad necesaria para cualquier hipervínculo que necesitemos: desde direcciones Web normales, de la forma "http://...", pasando por enlaces a partes específicas ("#nombredelancla"), e incluso a otros nodos.

Nos pararemos en la parte específica a XMLEye. Podemos crear un enlace entre un nodo y otro usando la sintaxis "#xpointer(ruta)", donde ruta es la ruta absoluta e unívoca del nodo anterior desde la raíz. Como esto no es tan fácil de implementar, disponemos en el nombre de espacios "xalan://es.uca.xmleye.xpath.GestorRutasXPath" de la función obtenerRuta, que hace precisamente eso.

Para usarla, añadimos la declaración de dicho nombre de espacios al elemento xsl:stylesheet y ya podemos usarla así, por ejemplo:

<xsl:template match="encapsulate|local" mode="ppacl2_printnode">
  <h2 class="section">
    <a href="#xpointer({rutasxpath:obtenerRuta(.,/)})">
      <xsl:value-of select="name(.)"/>
    </a>
  </h2>
  <pre>
    <xsl:value-of select="@formula"/>
  </pre>
</xsl:template>

Como vemos, la función toma dos argumentos: el primero es el nodo al cual queremos crear el enlace (aquí el nodo actual), y el segundo es el nodo que vamos a tomar como raíz (el nodo raíz, valga la redundancia).

Si tenemos que crear un enlace a un nodo de otro documento, la sintaxis es muy parecida: "rutadelfichero#xpointer(rutaxpath)", donde ahora indicamos tanto la ruta del fichero como la ruta XPath que queremos visualizar dentro de él.

Bibliografía

[1] Control de versiones con Subversion. Ben Collins-Sussman, Brian W. Fitzpatrick, y C. Michael Pilato. 2007.

[2] Software/shared-mime-info. Freedesktop.org. 2008.

Apéndice A. GNU Free Documentation License

Copyright (C) 2000, 2001, 2002 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

0. PREAMBLE

The purpose of this License is to make a manual, textbook, or other functional and useful document “free” in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.

This License is a kind of “copyleft”, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.

We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.

1. APPLICABILITY AND DEFINITIONS

This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The “Document”, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as “you”. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.

A “Modified Version” of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.

A “Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document's overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.

The “Invariant Sections” are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.

The “Cover Texts” are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.

A “Transparent” copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not “Transparent” is called “Opaque”.

Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.

The “Title Page” means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, “Title Page” means the text near the most prominent appearance of the work's title, preceding the beginning of the body of the text.

A section “Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.) To “Preserve the Title” of such a section when you modify the Document means that it remains a section “Entitled XYZ” according to this definition.

The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.

2. VERBATIM COPYING

You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.

You may also lend copies, under the same conditions stated above, and you may publicly display copies.

3. COPYING IN QUANTITY

If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.

If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.

If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.

It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.

4. MODIFICATIONS

You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:

  1. Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as a previous version if the original publisher of that version gives permission.
  2. List on the Title Page, as authors, one or more persons or entities responsible for authorship of the modifications in the Modified Version, together with at least five of the principal authors of the Document (all of its principal authors, if it has fewer than five), unless they release you from this requirement.
  3. State on the Title page the name of the publisher of the Modified Version, as the publisher.
  4. Preserve all the copyright notices of the Document.
  5. Add an appropriate copyright notice for your modifications adjacent to the other copyright notices.
  6. Include, immediately after the copyright notices, a license notice giving the public permission to use the Modified Version under the terms of this License, in the form shown in the Addendum below.
  7. Preserve in that license notice the full lists of Invariant Sections and required Cover Texts given in the Document's license notice.
  8. Include an unaltered copy of this License.
  9. Preserve the section Entitled “History”, Preserve its Title, and add to it an item stating at least the title, year, new authors, and publisher of the Modified Version as given on the Title Page. If there is no section Entitled “History” in the Document, create one stating the title, year, authors, and publisher of the Document as given on its Title Page, then add an item describing the Modified Version as stated in the previous sentence.
  10. Preserve the network location, if any, given in the Document for public access to a Transparent copy of the Document, and likewise the network locations given in the Document for previous versions it was based on. These may be placed in the “History” section. You may omit a network location for a work that was published at least four years before the Document itself, or if the original publisher of the version it refers to gives permission.
  11. For any section Entitled “Acknowledgements” or “Dedications”, Preserve the Title of the section, and preserve in the section all the substance and tone of each of the contributor acknowledgements and/or dedications given therein.
  12. Preserve all the Invariant Sections of the Document, unaltered in their text and in their titles. Section numbers or the equivalent are not considered part of the section titles.
  13. Delete any section Entitled “Endorsements”. Such a section may not be included in the Modified Version.
  14. Do not retitle any existing section to be Entitled “Endorsements” or to conflict in title with any Invariant Section.
  15. Preserve any Warranty Disclaimers.

If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version's license notice. These titles must be distinct from any other section titles.

You may add a section Entitled “Endorsements”, provided it contains nothing but endorsements of your Modified Version by various parties--for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.

You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.

The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.

5. COMBINING DOCUMENTS

You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.

The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.

In the combination, you must combine any sections Entitled “History” in the various original documents, forming one section Entitled “History”; likewise combine any sections Entitled “Acknowledgements”, and any sections Entitled “Dedications”. You must delete all sections Entitled “Endorsements”.

6. COLLECTIONS OF DOCUMENTS

You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.

You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.

7. AGGREGATION WITH INDEPENDENT WORKS

A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an “aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation's users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.

If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document's Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.

8. TRANSLATION

Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.

If a section in the Document is Entitled “Acknowledgements”, “Dedications”, or “History”, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.

9. TERMINATION

You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

10. FUTURE REVISIONS OF THIS LICENSE

The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.

Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License “or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.