XML Prague 2013

XML Prague is over…


The XML Prague 2013 team

As usual it’s very difficult to go back to work after these three intense days of deeply technical friendly exchange. The feeling is well known by attendees and has been described by Alex Milowski has Post XML Prague depression!

Unlike previous years I will not publish a post covering the whole conference (I am too busy at the moment) but will rather publish several short articles on specific topics.
Stay tuned! In the meantime you may want to have a look at my pictures.

Prend le gaz de schiste et tire toi

Le 15 novembre dernier, Les Matins de France Culture recevaient Corinne Lepage. Je n’ai pas eu le temps de le faire, mais j’aimerais revenir sur ce haut moment de radio qui me semble bien résumer le débat actuel autour de ce qu’on appelle « hydrocarbures non conventionnels ».

Le débat a opposé Corinne Lepage au chroniqueur Brice Couturier secondé par l’économiste Agnès Bénassy-Quéré. Il était arbitré par le producteur/présentateur Marc Voinchet et  le journaliste politique Frédéric Métézeau.

Vous pouvez retrouver cette émission sur le site de France Culture,la réécouter ou la télécharger. Pour que vous puissiez juger par vous même, je publie également la transcription de la partie qui traite des gaz de schiste à la fin de cet article. Elle se commence 1h49:25 après le début du fichier mp3 téléchargeable sur le site de France Culture.

Le métier des chroniqueurs est de savoir tout sur tout, d’avoir toujours raison et de ne pas admettre la contradiction. La chronique de Brice Couturier a fait l’apologie des gaz de schistes en utilisant quelques arguments imparables :

  •  « les États-Unis qui sont déjà les premiers producteurs de gaz au monde vont devenir dès la fin de cette décennie les premiers producteurs de pétrole en passant de 8 millions de barils par jour aujourd’hui à 12 millions en 2020 »
  • « Pouvons nous à la fois fermer des centrales nucléaire, renoncer à toute forme d’exploitation des gaz non conventionnels et prétendre réduire nos émissions de CO2 ? »
  • « Des entreprises françaises comme Total, Vallourec ou Solvay sont déjà en pointe dans cette technologie ».
  • « On sait qu’au sein même du gouvernement Arnaud Montebourg ou Alain Vidalies le souhaitent, mais il s’agit là pour les écologistes qui l’ont fait savoir d’un casus belli. Alors la logique politicienne doit elle l’emporter sur la logique industrielle ? »

Les chiffres indiqués par Brice Couturier concernant les États-Unis sont tirés d’un récent rapport de l’Agence Internationale de l’Énergie décortiqué par un article des Échos. Par contre Solvay n’est pas une entreprise française. Créé par un inventeur Belge, cette société se définit comme « internationale » et son siège social est à Bruxelles.

La question avec laquelle il clôt sa chronique (« la logique politicienne doit elle l’emporter sur la logique industrielle ? ») est symptomatique. Pourquoi utiliser un terme aussi négatif que « politicien »? Si l’on écoute les écologistes, c’est nécessairement pour des raisons politiciennes? C’est le type de questions auxquelles on s’attend sur Europe 1 ou sur ce qu’est devenu France Inter, mais sur France Culture, pourquoi ne pas avoir posé une vrai question telle que « le politique doit-il l’emporter sur l’industriel (ou l’économie ou la finance)? »?

Semblant être un moment décontenancée,  Corinne Lepage évacue la question (« La question ce n’est pas de savoir si ça fait plaisir aux verts ou si ça fait pas plaisir aux verts. La question est de savoir si c’est notre intérêt ou si ce n’est pas notre intérêt. ») et cherche une première fois à orienter le débat vers le problème de fond :

Le problème est, alors là je ne parle pas pour la France, je parle de problème général, nous allons directement à l’opposé de ce que nous voulions faire collectivement lorsque nous avons dit « pour lutter contre les gaz à effet de serre il faut sortir de la société du pétrole ». Là nous nous enfonçons dans la société du pétrole. Cela veut donc dire que nous prenons délibérément le risque en rajoutant 30, 40, 50, 60 pour-cents, je n’en sais rien, d’hydrocarbures supplémentaires d’augmenter la température non pas de 3 ou 4 degrés à la fin du siècle mais beaucoup plus et de mettre en péril carrément tout notre système. Ça c’est pas vrai seulement pour la France, c’est un problème global, autrement dit, vous parliez d’émission de gaz à effet de serre, pour moi c’est le problème numéro un. Et vous savez comme moi que l’exploitation des gaz de schiste, c’est des émissions de méthane en quantité absolument industrielle, le méthane, la tonne de méthane étant vingt-quatre fois plus grave pour l’effet de serre que la tonne de CO2.

Elle cherchera ainsi plusieurs fois à expliquer que l’exploitation d’hydrocarbures non conventionnels ne fait que prolonger un comportement suicidaire et à revenir sur la nécessité de réduire nos besoins en hydrocarbures pour éviter une catastrophe écologique.

Ses contradicteurs ne lui répondront jamais sur ce point. Sans se donner la peine de contester le réchauffement climatique, ils préfèrent l’ignorer!

Lors d’un échange particulièrement confus où Corinne Lepage et Brice Couturier se coupent mutuellement plusieurs fois la parole, celui-ci montre clairement le peu d’importance qu’il accorde à cet argument majeur qui devrait pourtant se suffire à lui même :

On voulait sortir du pétrole parce qu’il n’y en avait plus, maintenant on nous dit qu’il y en a encore, voyez c’est ça le problème, maintenant on nous dit il y en a encore pour cent ans donc c’est bizarre de reprendre l’argumentation il faut sortir du pétrole.

Corinne le Page tente alors une nième fois de se faire comprendre :

Non monsieur, excusez moi monsieur Couturier. On n’a pas dit ça, on a dit on est obligé de sortir du pétrole parce qu’on en a plus, et on doit en sortir à cause des émissions de gaz à effet de serre, parce que nous devons impérativement réduire les émissions de gaz à effet de serre de manière à ne pas augmenter de manière déraisonnable la température à la surface du globe.

Elle ne pourra terminer son argumentation sans que Brice Couturier lui coupe à nouveau la parole pour détourner la conversation.

Vers la fin du débat, alors que l’on semblait tourner en rond, Frédéric Métézeau sauve un peu la situation en abordant la question des explorations, donnant l’occasion à Corine Lepage de dénoncer l’hypocrisie de ces contrats dits « d’exploration » :

le problème c’est que, en droit quand vous avez un droit d’exploration vous avez derrière un droit d’exploitation, c’est comme cela que ça marche, il n’y a plus d’appel à la concurrence, c’est terminé. C’est à dire qu’il suffit de délivrer des permis d’exploration à toute une série de gens, ils peuvent geler les terrains pour des années et des années et de toute façon ils auront l’exploitation derrière. …/… Je pense que la recherche c’est à l’état de la faire, alors ensuite qu’il la contrôle, qu’il la fasse pas nécessairement directement mais qu’il la contrôle de manière qu’il n’y ait aucun droit de nature patrimoniale sous quelque forme que ce soit qui soit donné à qui que ce soit tant que l’on ne sait pas ce que l’on fait.

Cela provoque de vives réactions de la part d’Agnès Bénassy-Quéré : « mais alors, comment est-ce que l’état va inciter les entreprises à travailler à fond perdu ? » et de Brice Couturier « c’est une façon de fermer la porte de dire ça, hein, c’est une façon de dire puisque personne n’y aura intérêt personne ne le fera, hein, c’est une façon de fermer ».

Autrement dit, il est hors de question que notre pays investisse pour évaluer les ressources de son sous sol et il est inévitable que l’on accorde des permis « d’exploration » qui donnent des droits d’exploitation que l’on ne pourra plus contrôler…

J’ai gardé l’échange qui m’a fait le plus bondir, celui qui justifie ce long article pour la fin…

Corine Lepage ayant suggéré qu’il n’était peut être pas très urgent d’exploiter les gaz de schiste, Brice Couturier cite Louis Gallois : « Ce que dit Louis Gallois, il dit que si l’on attend trop, justement, on risque de se priver d’une grande part de ressource économique ». Corinne Lepage répond placidement « bah attendez ça partira pas, donc si c’est là c’est là ».

Cela semble évident, mais Agnès Bénassy-Quéré relance le débat dès qu’on lui donne la parole :

Les pays qui ont beaucoup de pétrole ne font pas ce raisonnement. Au contraire, ils veulent sortir leur pétrole relativement vite de leur sol parce que ils se disent il va y avoir une nouvelle révolution industrielle dé-carbonée, l’invention, on l’a pas l’innovation énergétique, euh, l’éolien c’est pas ça, le photo voltaïque c’est pas ça, on l’aura un jour peut être et ils se disent là il y a une fenêtre dans laquelle on va gagner beaucoup d’argent en sortant notre pétrole, mais ce ne sera pas éternel. Donc il y un risque que la France rate une période où il n’y a pas justement cette nouvelle innovation qui nous manque pour faire la croissance verte, qui va venir peut être mais qu’on n’a pas pour l’instant, elle rate cette fenêtre et donc le gaz, pourquoi pas, il restera éternellement sous nos pieds.

Je n’avais jamais entendu cet argument aussi clairement et cyniquement exposé!

Autrement dit : « prenons le gaz de schiste et tirons nous » ou encore « on sait que l’on ne va pas pouvoir continuer à emmètre des gaz à effet de serre très longtemps et que des empêcheurs de polluer en rond vont finir par obtenir gain de cause alors dépêchons nous de brûler le plus d’hydrocarbures possible le plus rapidement possible tant qu’il en est encore temps ».

J’imagine que ces gens là ont du faire les soldes pour isoler leur maisons à l’amiante et les repeindre avec des peintures au plomb juste avant qu’on interdisse ces produits!

Si vous avez encore un peu de temps, lisez la transcription : je trouve ce débat édifiant.

Transcription

France Culture 15 novembre 2012

Note : je n’ai pas voulu « éditer » les paroles échangées lors du débat mais ai au contraire cherché à en faire une transcription aussi fidèle que possible.

1:49:25 MV : Et à huit heures et 18 minutes, je vous rappelle donc, émission politique du matin, aujourd’hui Corine Lepage (CLP) avec Frédéric Métézeau, c’est l’heure de la chronique de Brice Couturier où je vous sens mettre les gaz..

1:49:25 BC : (rires) C’est l’expression, oui, Marc. Écoutez, vous savez peut-être que le ministre des finances vient de l’annoncer, je le cite, je cite le ministre des finances, « nous discutons actuellement d’un nouveau régime fiscal généreux pour encourager le gaz de schiste afin de rester compétitifs vis à vis des États-Unis ». Des incitations fiscales pour l’exploitation de gaz de schiste tels que ceux qui favorisent à prix d’or l’installation d’éoliennes et de panneaux photo-voltaïques ? Allons, allons, rassurez vous les écologistes, il ne s’agit pas de Pierre Moscovici. Non, ce n’est pas du ministre français des finances qu’il s’agit, encore moins d’ailleurs du ministre des finances allemand, même si celui-ci a tendance ces temps ci à s’inquiéter de l’envolée de la facture électrique de l’Allemagne pour cause de tournant énergétique. Mais des élections ont lieu l’an prochain chez nos voisins et la chancelière chrétienne-démocrate est prête à former une coalition avec les verts actuellement crédités de 15 % des intentions de vote. Non, le ministre des finances en question c’est le britannique George Osborne. Chez nous c’est un sujet qui est resté longtemps absent du débat publique mais il est en train d’y faire une percée remarquable. l’Amérique du nord, tant les États-Unis d’Obama que le Canada ont mis en exploitation leurs énormes réserves de gaz et de pétrole non conventionnels. C’est une révolution dans le domaine de l’énergie. Elle a déjà et elle aura des conséquences auxquelles nous ferions bien de réfléchir. Parce que les États-Unis qui sont déjà les premiers producteurs de gaz au monde vont devenir dès la fin de cette décennie les premiers producteurs de pétrole en passant de 8 millions de barils par jour aujourd’hui à 12 millions en 2020. Ils vont cesser complètement de dépendre des approvisionnements pétroliers du Golfe Persique et cela ne sera pas sans incidence sur leur diplomatie. Il n’y aura plus de guerre pour le pétrole, ou plutôt, assurer la liberté de circulation des voies maritimes entre Golfe Persique et Canal de Suez ne sera plus de leur ressort mais de celui des importateurs de pétrole que nous sommes nous les chinois et les européens en particulier. En aurons nous la volonté et les moyens ? Ensuite parce que l’énergie bon marché fournie aux entreprises par ce nouveau moyen n’est pas pour rien dans la ré-industrialisation menée avec succès par Obama et elle explique en partie les relocalisations dont les États-Unis bénéficient en ce moment. Entre parenthèses, le fameux peak oil que le club de Rome prévoyait aux alentours de 1980 et que l’on a cru à nouveau venu vers 2008 semble reculer toujours plus grâce à de nouvelles techniques d’extraction donc méfions nous des peak oils. Mais celles ci, ces techniques d’exploitation, se révèlent de plus en plus problématiques. C’est vrai, l’exploitation des gaz de schiste par la technique du forage directionnel horizontal et d’hydro-fracturation est polluante. En particulier parce qu’elle nécessité l’usage de millions de litres d’eau auxquels on ajoute des produits chimiques dont nul ne sait s’ils ne vont pas se répandre dans les nappes phréatiques si les puits ne sont pas suffisamment étanches. En outre les roches fracturées par ce procédé libèrent des substances toxiques. Alors oui, il faut faire preuve de prudence mais un pays comme le notre qui recèlerait cent fois sa consommation annuelle de gaz dans son sous sol peut il renoncer absolument à toute exploration ? Pouvons nous à la fois fermer des centrales nucléaire, renoncer à toute forme d’exploitation des gaz non conventionnels et prétendre réduire nos émissions de CO2 ? Des entreprises françaises comme Total, Vallourec ou Solvay sont déjà en pointe dans cette technologie, toutes sortes de bons esprits, de Louis Gallois à Michel Rocard plaident pour que notre pays ne referme pas la porte d’une exploitation raisonnable des énormes réserves énergétiques que nous avons sous nos pieds. On sait qu’au sein même du gouvernement Arnaud Montebourg ou Alain Vidalies le souhaitent, mais il s’agit là pour les écologistes qui l’ont fait savoir d’un casus belli. Alors la logique politicienne doit elle l’emporter sur la logique industrielle ?

1:53:25MV : La chronique de Brice Couturier, à retrouver sur franceculture.fr. Corinne Lepage :

1:53:30 CLP Oui… Euh… Alors, je.. On me dirait, monsieur Couturier, sur votre dernière phrase, la logique politicienne doit elle l’emporter sur la logique industrielle, je répondrais évidemment non. Mais c’est pas de ça dont il s’agit à mes yeux. La question ce n’est pas de savoir si ça fait plaisir aux verts ou si ça fait pas plaisir aux verts. La question est de savoir si c’est notre intérêt ou si ce n’est pas notre intérêt. Moi c’est comme cela que je pose la question, je ne la pose pas autrement. Alors, premier point, je dirais un point général. Vous avez parlé du peak-oil. Il a eu effectivement lieu pour le conventionnel en 2006, à peu près, 2006 – 2007. Donc maintenant si effectivement on parle de réserves pour des dizaines d’années, c’est précisément par ce qu’on recourt à tout ce que l’on appelle les hydrocarbures non conventionnels, gaz et pétrole, sables bitumineux au Canada, etc, etc… Le problème est, alors là je ne parle pas pour la France, je parle de problème général, nous allons directement à l’opposé de ce que nous voulions faire collectivement lorsque nous avons dit « pour lutter contre les gaz à effet de serre il faut sortir de la société du pétrole ». Là nous nous enfonçons dans la société du pétrole. Cela veut donc dire que nous prenons délibérément le risque en rajoutant 30, 40, 50, 60 pour-cents, je n’en sais rien, d’hydrocarbures supplémentaires d’augmenter la température non pas de 3 ou 4 degrés à la fin du siècle mais beaucoup plus et de mettre en péril carrément tout notre système. Ça c’est pas vrai seulement pour la France, c’est un problème global, autrement dit, vous parliez d’émission de gaz à effet de serre, pour moi c’est le problème numéro un. Et vous savez comme moi que l’exploitation des gaz de schiste, c’est des émissions de méthane en quantité absolument industrielle, le méthane, la tonne de méthane étant vingt-quatre fois plus grave pour l’effet de serre que la tonne de CO2. Ça c’est le premier point.

1:55:23 BC: (lui coupant la parole) D’autres avancent d’autres chiffres en disant que la question des gaz à effet de serre est moindre avec l’exploitation des gaz de schistes.

1:55:29 CLP : Alors, ils comparent par rapport au charbon, mais c’est pas sur parce que le charbon c’est pas du méthane c’est du CO2 et là on a du méthane et le méthane c’est beaucoup plus grave. Et donc vous parliez de fuites et vous avez raison au niveau des nappes phréatiques, mais c’est des fuites de méthane aussi de manière indéfinie. Donc on a un problème général. Deuxièmement, si la France a ce trésor sous les pieds, il va pas partir, il va pas s’enfuir. Vous savez comme moi que c’est pas parce que une baguette magique arriverait et on dirait d’accord, OK, on ouvre les vannes et on fait de l’exploration, vous savez très bien que sur le plan de l’économie française, 2012-2013 c’est effet 0, c’est pas pour maintenant, c’est pour dans plusieurs années, dans 7 ans, 8 ans, j’en sais rien, le temps qu’il faudrait pour faire de l’exploration et passer à une phase d’exploration, autrement dit aucun effet sur la situation économique actuelle. Donc je pense que 1) c’est gravissime, pour moi c’est une régression majeure

1:56:26 BC : (lui coupant la parole) Ce que dit Louis Gallois, il dit que si l’on attend trop, justement, on risque de se priver d’une grande part…

CLP : ben ça partira pas

BC : ressource économique

CLP : bah attendez ça partira pas, donc si c’est là c’est là moi si vous voulez, ce qui me fait très peur c’est tout les procédés autour et alentours, donc on fait pas de fracturation, mais on va aller chercher du pétrole, c’est ce qui se passe sous le Bassin Parisien, les sociétés pétrolières présentent ça sous une autre forme pour essayer de passer, etc, bon personne n’est dupe quand même, première observation. Deuxième observation, c’est les conséquences, nous sommes quand même pas les États-Unis, la France c’est pas le Texas, il a pas du tout les mêmes espaces, il y a des conflits, il va y avoir des conflits d’usage d’eau, des conflits d’usage de territoire, des problèmes sur l’activité agricole et agro-alimentaire etc, etc. Donc très franchement, je pense que sur le plan global c’est une catastrophe pour l’humanité et deuxièmement c’est franchement les avantages ne l’emportent certainement pas sur les inconvénients.

1:57:31MV : « Écologie, économie » disiez vous en première partie, comment concilier les deux, Corinne Lepage, alors comment fait on et débrouille t-on la question de ce que les entreprises françaises sont en pointe sur la question du gaz de schiste à l’étranger, pourquoi ne le seraient elles pas en France ?

1:57:45 CLP : Oui, enfin ça je vais vous dire, on est en face d’une telle

MV : (lui coupant la parole) Je vais vous donner… dans les échos d’aujourd’hui il y a un très bon dossier sur la question d’ailleurs qui fait…

CLP : nos journaux actuellement, ou tout du moins certains d’entre aux ont d’excellents dossiers, extrêmement bien montés, nous sommes en face d’une campagne, pour être correcte je dirais d’information, j’aurais peut être envie de dire un autre mot qui serait désinformation, mais restons sur l’information, extrêmement bien ciselée, on le voir partout, on l’entend partout, et tout est fait pour essayer de faire changer les français d’avis. Sauf que personne en France n’a envie d’avoir une exploitation de gaz de schiste à côté de chez lui, y compris…

1:58;23 MV : On est d’accord pour en acheter à l’étranger. Il y a un paradoxe tout de même

CLP : Parce que les conséquences… c’est des conséquences environnementales. Il y a deux types de conséquences, les conséquences planétaires dont je parlais tout à l’heure qui pour moi plaident en défaveur des gaz de schiste de manière…

MV ; on préfère que les autres exploitent par ailleurs des gaz de schistes que chez nous. Enfin on va en acheter tout de même !

CLP : Oui, on achète du pétrole parce qu’on en a pas vraiment chez nous…

BC : Mais là justement on en a. Je cite Rocard, Michel Rocard, c’est quand même pas un va t-en guerre ultra libéral victime des lobbys pétroliers ! Voilà ce qu’il dit, Michel Rocard dans le monde

CLP : Oui, j’ai lu

BC : « La France est bénie des dieux, pour l’Europe elle serait au gaz se schiste ce que le Qatar est au pétrole, peut-on s’en priver ? Je ne le crois pas. » C’est du Rocard.

1:59:02 CLP : Oui, c’est du Rocard et d’un autre côté il dit «je suis écologiste et donc je suis très partagé » donc on cite que cette partie là et on cite pas l’autre où il est quand même beaucoup plus mesuré. Autrement dit vous risquez, en dehors de la question majeure qui pour moi est d’investir massivement pour sortir du pétrole, et je pense que nous sommes aussi une terre bénie des dieux pour le faire parce que nous avons tout ce qu’il faut en terme

BC : On voulait sortir du pétrole parce qu’il n’y en avait plus, maintenant on nous dit qu’il y en a

CLP : non, non, non

BC : encore, voyez c’est ça le problème

CLP : pas du tout

BC : maintenant on nous dit il y en a encore pour cent ans

CLP : non

BC : donc c’est bizarre de reprendre l’argumentation il faut sortir du pétrole

CLP : Non monsieur, excusez moi monsieur Couturier. On n’a pas dit ça, on a dit on est obligé de sortir du pétrole parce qu’on en a plus, et on doit en sortir à cause des émissions de gaz à effet de serre, parce que nous devons impérativement réduire les émissions de gaz à effet de serre de manière à ne pas augmenter de manière déraisonnable la température à la surface du globe. Vous vous rendez compte de

BC : vous vous rendez compte que pendant ce temps à les allemands sur la base du même principe sont en train de polluer toute l’Europe avec du charbon, parce que comme il ont renoncé

CLP : de moins en moins

BC : comme on renonce à la fois au nucléaire et on renonce au gaz de schiste on renonce à tout finalement et qu’est ce qui reste, le charbon et

CLP : non, pas du tout

BC : c’est quand même la calamité absolue le charbon

CLP : ils réduisent

BC : et les chinois aussi ils utilisent

CLP : alors premièrement ils

MV : Corine Lepage

CLP : ils ont des procédés d’utilisation du charbon qui sont quand même beaucoup moins polluants qu’ils n’étaient et deuxièmement je vous donne rendez vous dans cinq ou dix ans quand vous allez avoir une industrie allemande qui va être partout leader sur tout les nouveaux marchés qui vont être ceux de efficacité énergétique et des énergies renouvelables et que nous on sera encore à nous poser des questions sur les gaz de schistes et à continuer sur le nucléaire

BC : Mais tout de même, Corinne Lepage, mettant autant d’énergie à luter contre l’exploitation des gaz en France qu’on devrait en mettre par exemple sur le fait que les compagnies pétrolières du monde entier, notamment françaises, détruisent un pays comme le Nigeria aujourd’hui dont on ne résout toujours pas toutes les questions où les … sont effectivement morts, dont la population est accablée de toutes les maladies et où personne, strictement personne ne fait rien, au nom de notre indépendance énergétique.

CLP : Je suis complètement d’accord avec vous

BC …

CLP : oui, mais au Nigeria il s’est quand même passé une chose très intéressante c’est que BP s’est fait condamner à une amende absolument massive par les tribunaux nigérians

BC : encore faudra t-il qu’elle la paye

CLP : Oui c’est possible, mais n’empêche que, je revient un peu à mon dadas, on parlait tout à l’heure de la société civile, qu’est-ce qui est en train d’essayer de réorganiser un peu les pouvoirs dans ce monde, c’est la société civile et la justice. Parce que vous avez le Nigeria effectivement pour le pétrole et vous avez dans d’autres pays aussi du sud, où vous avez des actions de ce genre qui sont menées. Donc, je crois que les citoyens se rendent tout à fait compte de ce qui est en train de se passer. Et je suis très, très attentive aux questions de l’économie

BC : Beee

CLP Je me dis

MV : Attendez, justement je vais passer la parole à Agnès Bénassy-Quéré. Economie/écologie, est-ce que dans cette question des gaz de schistes on est dans des conflits insolubles

2:02:00 ABQ : je voulais revenir rapidement sur le gaz ne va pas s’échapper, il est sous nos pieds, il va rester

CLP : Oui, et bah oui

ABQ : C’est un argument qui est tout à fait bon si par exemple on fait de la recherche par exemple pour voir s’il y une autre technique. Bon je sais qu’il y a des problèmes avec le code minier, etc. Mais sinon ça ne sert à rien, les pays qui ont beaucoup de pétrole ne font pas ce raisonnement. Au contraire, ils veulent sortir leur pétrole relativement vite de leur sol parce que ils se disent il va y avoir une nouvelle révolution industrielle dé-carbonée, l’invention, on l’a pas l’innovation énergétique, euh, l’éolien c’est pas ça, le photo voltaïque c’est pas ça, on l’aura un jour peut être et ils se disent là il y a une fenêtre dans laquelle on va gagner beaucoup d’argent en sortant notre pétrole, mais ce ne sera pas éternel. Donc il y un risque que la France rate une période où il n’y a pas justement cette nouvelle innovation qui nous manque pour faire la croissance verte, qui va venir peut être mais qu’on n’a pas pour l’instant, elle rate cette fenêtre et donc le gaz, pourquoi pas, il restera éternellement sous nos pieds.

CLP : Alors je vais répondre à cela. D’abord vous dites on l’a pas, moi je vois quand même ce qui se passe au niveau européen, je vous des pays comme l’Allemagne qui disent nous allons être à 40 % d’énergie renouvelable en 2020, c’est à dire demain matin, par conséquent je pense au contraire que, notamment sur l’éolien offshore, je pense sur les énergies marines, je pense sur le photo voltaïque je pense bien sur que les sociétés européennes sont en difficulté parce que le prix des cellules a chuté à cause des chinois dans des proportions tout à fait considérables, mais aujourd’hui vous avez un kW/h éolien qui est inférieur au kW/h qui sortira des nouvelles centrales nucléaires. Donc je crois qu’on peut pas dire qu’on y est pas, je pense précisément qu’on est en train d’y être et ce qui m’inquiète c’est les choix énergétiques que la France est en train de faire sur le plan industriel. Je parle pas d’écologie là, je parle d’industrie, je pense que nous sommes en train de louper précisément cette grande fenêtre de tir. Vous parliez d ‘énergie dé-carbonée, c’est précisément tout cela et ce qui se joue aujourd’hui c’est cale. Faut bien comprendre qu’investir massivement dans les gaz de schiste c’est quoi ? C’est avoir très vite une énergie qu’on va pas payer très cher même si on va la payer beaucoup plus cher qu’aux États-Unis contrairement à ce qu’on nous raconte parce que même aux États-Unis aujourd’hui on va être obligé de capter le méthane ce qui n’était pas le cas jusqu’à maintenant donc vous allez avoir un coût beaucoup plus élevé puis aux États-Unis vous avez des actions en réparation et les compagnies pétrolières elles vont payer pour les dommages immenses qu’elles on causé et donc c’est maintenant que la facture va venir, mais ça c’est un détail, mais vous allez avoir une difficulté de rentabilité des énergies renouvelables, précisément parce que vous allez avoir pendant un court moment une énergie qui va être probablement moins chère, ça c’est vrai mais avec des conséquences irréversibles ou très chères que nous allons payer après donc je ne suis pas sure que ce soit notre intérêt. Moi je suis fermée à rien, là où je ne suis pas d’accord, c’est quand on a des dés pipés, qu’on arrive pas à avoir des évaluations économiques correctes, des avantages et des inconvénients des différentes solutions.

2:04:58 MV : Mais, a t-on une évaluation scientifique, je pose la question sans malice, correcte ? Parce que on entend bien, absolument, ceux qui disent c’est très dangereux, voilà, et on en entend d’autres, alors, est-ce qu’ils sont soumis à des lobbys ou pas, je n’en sais rien mais on entend

BC : Mais pourquoi les premiers ne seraient pas aussi soumis à des lobbys ?

CLP : parce qu’ils ne cherchent pas d’argent

MV : … dans le Monde disait qu’il est possible d’exploiter je cite, proprement le gaz de schiste moyennant de gros investissements technologiques, il a rajouté, voilà, le jeu en vaut la chandelle a t-il affirmé.

CLP : Écoutez, moi j’en sait rien. On a auditionné beaucoup de gens au parlement européen puisque moi je suis rapporteur sur le texte sur les gaz de schiste, je peux vous dire qu’on est en face d’un lobbying absolument démentiel

BC : Mais il y a un lobbying des deux côtés, il y a un lobbying de l’éolien qui est très efficace aussi, hein

CLP :…

BC : Ah oui, hein

CLP : Il est beaucoup plus petit et je peux vous dire qu’ils se font beaucoup moins entendre que les autres et ils ont beaucoup moins de moyens

BC : Auprès des médias je peux vous dire que c’est assez équivalent

CLP : Peut être mais auprès des députés c’est pas de même niveau et donc pour l’instant on est entrain d’essayer de nous empêcher

MV : en tout cas ils ont fait du lobbying pour éviter André de Margerie ici et il n’est toujours pas venu

CLP : de nous empêcher de passer une législation, parce que voyez vous s’il y avait une législation, le minimum c’est qu’il y ait une étude d’impact, c

BC : Vous demandez quoi précisément qu’on comprenne bien, sur la question

CLP : une législation

BC : sur la question de la sûreté, de la sécurité

CLP : bon, et bien, à minima, mais je maintiens et je le redis parce que pour moi c’est essentiel, c’est rétrograde parce que l’on fait de la régression par rapport à une société post-pétrolière, pour moi, ça c’est majeur. Mais admettons qu’on aille dans cette direction là

BC : voilà !

CLP : Minimum : une étude d’impact, obligatoire au départ, un système de responsabilité illimité, pour tous les dommages causés et une obligation d’assurance

BC : C’est l’avocate qui parle

CLP : C’est le juriste

BC ; Le juriste, oui

CLP : Parce que c’est très facile d’aller cochonner et j’emploie un mot poli une région entière et ensuite de dire je suis en faillite et débrouillez vous, c’est ce qu’on eu avec Metaleurop, c’est ce qu’on a avec beaucoup de raffineries de pétrole, de sociétés de raffineries de pétrole qui vendent à des filiales ou d’autres sociétés qui n’ont pas un centime qui exploitent pendant un an, elles sont en faillite, et personne ne paie sauf vous et moi. Donc ça suffit. Par voix de conséquence, si on avait un système comme cela, c’est responsabilité illimitée et garanties financières qui vont avec. Et bien je vous assure que le coût il sera d’une autre nature que ce que l’on nous raconte aujourd’hui.

MV : Frédéric Métézeau

FM : Oui, Corine Lepage, deux éléments pour nourrir le débat : avant hier mardi, la plus grande centrale solaire a été mise en service en Lorraine par EDF, donc de l’argent public et dans votre tribune publiée dans le Monde ce même jour, mardi « gaz de schiste a ses lobbyistes » vous écrivez « si le gaz de schiste présente un enjeu stratégique pour la France, alors la recherche et le recensement public des réserves ne peut se faire que par l’état ». EDF d’un côté, l’état de l’autre, est-ce que cela veut dire que la politique énergétique et l’action énergétique doivent revenir dans le giron de l’état et pas dans des sociétés privées que ce soit une énorme boite ou une PME ?

2:07:53 CLP : Je vais vous dire ? Ce qui me fait peur dans l’affaire de l’exploration. Moi je comprend bien qu’on dise on veut savoir, c’est logique

MV: Donc c’est bien la question de l’exploration

CLP : Oui, le problème c’est que, en droit quand vous avez un droit d’exploration vous avez derrière un droit d’exploitation, c’est comme cela que ça marche, il n’y a plus d’appel à la concurrence, c’est terminé. C’est à dire qu’il suffit de délivrer des permis d’exploration à toute une série de gens, ils peuvent geler les terrains pour des années et des années et de toute façon ils auront l’exploitation derrière. Donc ça c’est pas possible donc c’est la raison pour laquelle, parce que je ne suis pas quelqu’un qui suit pas fermé, j’essaye encore une fois, … C’est pas politicien, le choix entre industrie et politicien, non, c’est quel est l’intérêt général des français. Donc si c’est ça je pense que la recherche c’est à l’état de la faire, alors ensuite qu’il la contrôle, qu’il la fasse pas nécessairement directement mais qu’il la contrôle de manière qu’il n’y ait aucun droit de nature patrimoniale sous quelque forme que ce soit qui soit donné à qui que ce soit tant que l’on ne sait pas ce que l’on fait.

ABQ : Mais alors, comment est-ce que l’état va inciter les entreprises à travailler à fond perdu ?

BC : C’est une façon de fermer la porte de dire ça, hein, c’est une façon de dire puisque personne n’y aura intérêt personne ne le fera, hein, c’est une façon de fermer

CLP : Non, bah heuh, ça peut être une négociation autour effectivement du code minier de la manière dont on rémunère un simple permis de recherche pour savoir si il y en a ou s’il n’y en a pas. Mais je crois que c’est quelque chose de très très important.

2:09:12 BC : Je voudrais revenir à l’économie parce que ça me paraît fondamental. Il faut comprendre qu’aujourd’hui si les États-Unis sont en train de se réindustrialiser et c’est une des raisons pour lesquelles Obama a été élu, c’est précisément que les industriels américains aujourd’hui paient leur énergie deux fois et demi moins cher que nous

CLP : c’est vrai, c’est vrai

BC : hors les allemands la payent beaucoup plus cher et c’est pas sans rapport avec leur transition énergétique. Il faut savoir qu’aujourd’hui effectivement vous avez raison le solaire, l’éolien et l’hydraulique représentent 20 % de la consommation allemande d’électricité contre 17 % l’année précédente. Bon 20 % c’est pas mal, l’objectif est de 35 %

CLP : Ils viennent de 6 ou 7, hein, ils viennent de très très loin.

BC : c’est vrai, c’est vrai mais en attendant la facture énergétique allemande est devenue tellement considérable que les industriels allemands s’inquiètent beaucoup de la traduction en terme de compétitivité de l’industrie allemande. Nous même qui avons un super problème de compétitivité bien plus grave que celui des allemands est-ce que nous pouvons de ne pas exploiter nos ressources énergétiques qui nous permettraient de faire baisser la facture de nos industriels.

CLP : On a une électricité qui est très bon marché en France.

BC : C’est vrai. Grâce au nucléaire.

CLP : Oui, grâce au nucléaire mais elle est très bon marché. Qu’on paie pas notre prix, ça c’est une autre affaire, mais juste un mot pour dire, vous parlez des entreprises, juste un mot pour les particuliers, le ménage allemand paie le kW/h beaucoup plus cher que le ménage français mais paie une facture qui est moins chère que la facture du ménage français parce que l’efficacité énergétique en Allemagne c’est 35 % supérieur à l’efficacité énergétique en France.

ABQ : Pour que le tableau soit complet, le ménage allemand paie son énergie beaucoup plus cher que l’entreprise allemande. Donc ça m’amène à la question : en France qui doit payer la transition énergétique ? Le gouvernement vient d’annoncer qu’il va y avoir une fiscalité écologique qui va arriver. Qui doit payer ça ? Est-ce que ce sont les ménages, avec un risque sur leur pouvoir d’achat ou est-ce que ce sont les entreprises avec un risque sur la compétitivité ?

MV : François Hollande a dit que cette transition devait conduire la France à devenir une société sobre en carbone à l’horizon 2050.

 

Il ne sera plus question de gaz de schiste pendant le reste de l’émission…

Installing Orbeon Forms, Tomcat and your application side by side on Ubuntu

One of the huge benefits of Debian based distributions (such as Ubuntu) is their packaging system that let you apply security updates on all the software that is installed on your system through a single command.

It is a strong motivation to prefer to install software through distribution packages rather than from their developer downloads and that applies to tomcat which is a common choice as a servlet container to power Orbeon Forms applications.

The Orbeon Forms’ installation guide describes two ways of installing on Tomcat. The first one is basically unzipping Orbeon Forms in the Tomcat’s webapp directory.

This is working fine, but rather than adding stuff to the /var/lib/tomcat7/webapps directory, I usually prefer to give Orbeon Forms its own location and use the second method « Apache Tomcat with a custom context« . If you are using the tomcat7 Ubuntu or Debian package, the context file (that can be called orbeon.xml) should go in the /etc/tomcat7/Catalina/localhost/ directory.

On my laptop, with Ubuntu 12.04 and Tomcat7, this configuration is working out of the box.

Now that we’ve installed Orbeon Forms physically « side by side » with Tomcat rather than within a Tomcat directory, what about installing your Orbeon Forms application side by side with Orbeon Forms rather than installing into the Orbeon Forms directories?

This is also possible using Orbeon Forms resource managers! This is a technique that is used in development mode and in web.xml you can find the following comment:

    <!-- Uncomment this for the filesystem resource manager (development mode) -->
    <!--
    <context-param>
        <param-name>oxf.resources.priority.1</param-name>
        <param-value>org.orbeon.oxf.resources.FilesystemResourceManagerFactory</param-value>
    </context-param>
    <context-param>
        <param-name>oxf.resources.priority.1.oxf.resources.filesystem.sandbox-directory</param-name>
        <param-value>/home/teamcity/TeamCity/buildAgent/work/278cc758fa087cef/src/resources</param-value>
    </context-param>-->
    <!-- End filesystem resource manager (development mode) -->

The context parameters that are commented basically say that resources will be searched in a specific directory (such as /home/teamcity/TeamCity/buildAgent/work/278cc758fa087cef/src/resources) before being searched in the Orbeon Forms WEB-INF/resource directory (which itself will be used before searching in the packages jar files, …).

To deploy your application side by side with the Orbeon Forms installation you can just uncomment these parameters and replace this directory by the location of your application. The documents that you’ll provide in this directory will then override the documents that might be in the Orbeon Forms installation.

There is probably a performance degradation associated with this mechanism but the benefits are really interesting: web.xml becomes the only file that you’ll update in the standard Orbeon Forms installation and changing Orbeon Forms versions becomes really easy.

 

Tout est à nous

Tout est à nous
Rien n’est à eux
Tout ce qu’ils ont
Ils l’ont volé
Partage des richesses
Partage du temps de travail
Ou sinon ça va péter

Cet après midi encore, cette chanson de manif m’a ému. Elle est simple et peut paraître naïve. Elle résume pourtant parfaitement la crise économique et écologique que nous traversons.

Cela fait des années qu’elle est scandée manif après manif. Si tant de monde partage ce constat, pourquoi rien ne change t-il?

Toward χίμαιραλ/superset

Background

Up to now, my approach to explore possible solutions to support JSON in XDM has been to evaluate the proposal to introduce maps in XSLT 3.0, leading to the χίμαιραλ proposal.

Finding out that in the current XSLT 3.0 Working Draft, JSON objects would be second class XDM citizens, I think that it’s worth considering other approaches and consider Jürgen Rennau’s UDL proposal has a very good starting point.

In their comments after Rennau’s presentation, John Cowan and Steven DeRose stressed out the need to forget about the serialization and focus on the data model, at least as a first step, when proposing alternative solutions.

Following their advise, I’d like to propose an update to core XDM 3.0 that would natively support JSON objects without introducing any new item kind.

Because this proposal is a chimera and because it’s a superset of the current XDM (any current XDM instance would be compatible with the updates I am proposing), I’ll call this proposal χίμαιραλ/superset.

The XDM carefully avoids to draw class models and prefers to specify nodes through nodes kinds and accessors. However, I think fair to say that elements are defined as nodes with three basic properties:

  • A mandatory name which is a QName.
  • A map of attributes which keys are QName.
  • An array of children nodes.

On the other hand, the JSON data model is composed of arrays, objects and atomic values. JSON atomic values can be numbers, strings, booleans or null. JSON key arrays can be any atomic values.

Traditional approaches to bind JSON and XML use XML element’s children to represent JSON object properties and UDL is no different in that matter.

There are obvious good reasons to do, the main one being that XML attribute values can only be atomic values while JSON object properties can also be maps or arrays.

However, the end result is that the interface mismatch resulting from binding JSON objects (which are maps) into XML children (which are arrays) is at the origin of most of the complexity of these proposals.

Proposal ( χίμαιραλ/superset)

Since XML elements already have both a map (of attributes) and an array (of children nodes), why not use these native features to bind JSON maps and arrays and just update the data model to remove the restrictions that make attribute maps and children arrays unfit for being bound respectively to JSON objects and arrays?

A JSON object would then just be bound to an XML element with attributes and without children nodes and a JSON array would be bound to an XML element with children nodes and without attribute.

This seems especially easy if we focus on the data model and postpone the (optional) definition of a serialization syntax.

First modification: elements can be anonymous

Neither JSON objects nor JSON arrays have name but XML elements have names and this name is mandatory.

To fix this issue, element names should become optional (in other words, we introduce the notion of anonymous elements).

Second modification: attribute names should also possibly be strings, booleans or null

If we bind JSON object keys on attribute names, it should be possible to use all the basic types that JSON accept for its keys.

Additionally, we may want to consider supporting other XML Schema simple types, possibly each of them.

To make this possible, the definition of the dm:node-name() accessor should be updated to return a typed values rather than a QName. This modification should concern attribute nodes at minima but for maximum homogeneity, we should probably extend that to other node types.

Third and last modification: attributes should have (optional) attributes and children

JSON object values can be objects and arrays and since objects are bound to attributes and arrays are bound to children, attributes should support both.

Mapping JSON into χίμαιραλ/superset

With these updates, binding JSON into XML become quite straightforward:

  • A JSON object is mapped into an anonymous element without children and one attribute per key/value pair.
  • A JSON array is mapped into an anonymous element without attribute and a child element per item.

Let’s take the now famous (at least on this blog) JSON snippet borrowed from the XSLT 3.0 Working Draft:

{ "accounting" : [
      { "firstName" : "John",
        "lastName"  : "Doe",
        "age"       : 23 },

      { "firstName" : "Mary",
        "lastName"  : "Smith",
        "age"       : 32 }
                 ],                                
  "sales"     : [
      { "firstName" : "Sally",
        "lastName"  : "Green",
        "age"       : 27 },

      { "firstName" : "Jim", 
        "lastName"  : "Galley",
        "age"       : 41 }
                  ]
}

Becomes:

  • Anonymous element without children and two attributes:
    • Attribute « accounting » (as a string) with no attributes and the two following children:
      • Anonymous element with no children and the three following attributes:
        • Attribute « firstName » (as a string) and a value « John » (as a string)
        • Attribute « lastName » (as a string) and a value « Doe » (as a string)
        • Attribute « age » (as a string) and a value 23 (as a number)
      • Anonymous element with no children and the three following attributes:
        • Attribute « firstName » (as a string) and a value « Mary » (as a string)
        • Attribute « lastName » (as a string) and a value « Smith » (as a string)
        • Attribute « age » (as a string) and a value 32 (as a number)
    • Attribute « sales » (as a string) with no attributes and the two following children:
      • Anonymous element with no children and the three following attributes:
        • Attribute « firstName » (as a string) and a value « Sally » (as a string)
        • Attribute « lastName » (as a string) and a value « Green » (as a string)
        • Attribute « age » (as a string) and a value 27 (as a number)
      • Anonymous element with no children and the three following attributes:
        • Attribute « firstName » (as a string) and a value « Jim » (as a string)
        • Attribute « lastName » (as a string) and a value « Galley » (as a string)
        • Attribute « age » (as a string) and a value 41 (as a number)

What do you think (comments very welcome)!

Fleshing the XDM chimera

Note: this article is derived from the presentation I have given at Balisage (precedings). See also the slides (and video) used during this presentation.

Abstract

The XQuery and XPath Data Model 3.0 (XDM) is the kernel of the XML ecosystem. XDM had been extended with foreign item types to embrace new data sources such as JSON, taking the risk to become a chimera. This talk explores some ways to move this fundamental piece of the XML stack forward.


Motivation

Chimera (mythology): The Chimera (also Chimaera or Chimæra) (Greek: Χίμαιρα, Khimaira, from χίμαρος, khimaros, « she-goat ») was, according to Greek mythology, a monstrous fire-breathing female creature of Lycia in Asia Minor, composed of the parts of multiple animals: upon the body of a lioness with a tail that ended in a snake’s head, the head of a goat arose on her back at the center of her spine. The Chimera was one of the offspring of Typhon and Echidna and a sibling of such monsters as Cerberus and the Lernaean Hydra. The term chimera has also come to describe any mythical animal with parts taken from various animals and, more generally, an impossible or foolish fantasy.
Wikipedia
Chimera (genetics): A chimera or chimaera is a single organism (usually an animal) that is composed of two or more different populations of genetically distinct cells that originated from different zygotes involved in sexual reproduction. If the different cells have emerged from the same zygote, the organism is called a mosaic. Chimeras are formed from at least four parent cells (two fertilized eggs or early embryos fused together). Each population of cells keeps its own character and the resulting organism is a mixture of tissues.
Wikipedia

During her opening keynote at XML Prague 2012, speaking about the relation between XML, HTML, JSON and RDF, Jeni Tennison warned us against the temptation to create chimeras: [chimera are usually ugly, foolish or impossible fantasies].

The next morning, Michael Kay and Jonathan Robie came to present new features in XPath/XQuery/XSLT 3.0. A lot of these features are directly based on the XQuery and XPath Data Model 3.0 (aka XDM):

The XPath Data Model is the abstraction over which XPath expressions are evaluated. Historically, all of the items in the data model could be derived directly (nodes) or indirectly (typed values, sequences) from an XML document. However, as the XPath expression language has matured, new features have been added which require additional types of items to appear in the data model. These items have no direct XML serialization, but they are never the less part of the data model.

XDM 3.0 is composed of items from a number of different technologies:

  • Items from the XML Infoset (nodes, attributes, …)
  • Datatype information borrowed from the Post Schema Validation Infoset
  • Sequences
  • Atomic values
  • Functions that can also be used to model JSON arrays
A note Note
The feature that will be introduced to model JSON arrays is called « maps » and it will be specified as a XSLT feature in the XSLT 3.0 recommendation (not published yet). The XSLT 3.0 editor, Michael Kay has published an early version of this feature in his blog. In this paper, XDM 3.0 will refer to the XSLT 3.0 data model (the XPath 3.0 data model augmented with maps).

XDM 3.0 being a single data model composed of items from different data models, it is fair to say that it is a chimera!

Following Jeni Tennison on stage, I have tried to show that in a world where HTML 5 on one hand and JSON on the other hand are gaining traction, XML has become an ecosystem in a competitive environment and that it’s data model is a major competitive advantage.

Among other factors, the continued success of XML will thus come from its ability to seamlessly integrate other data models such as JSON.

If we follow this conclusion, we must admit that this chimera is essential to the future of XML and do our best to make it elegant and smart.

XML Data Models

Whether it’s a bug or a feature could be debated endlessly, but a remarkable feature of the XML recommendation it’s all about syntax and parsing rule and does not really define a data model. The big advantage is that everyone can find pretty much what he wants in XML documents but for the sake of this paper we need to choose a well known -and well defined- data model to work on.

The most common XML data model is probably the data model defined by the trio XPath/XSLT/XQuery known as « XDM » since XPath version 2.0 and that’s the one we will choose.

XDM version 3.0, still work in progress, will be the third version of this data model. It’s important to understand its design and evolution to use its most advanced features and we’ll start our prospective by a short history of its versions.

XPath/XSLT 1.0

The XPath 1.0 data model is described as being composed of seven types of nodes (root, elements, text, attributes, namespaces, processing instructions and comments).

The XSLT 1.0 data model is defined as being the XPath 1.0 data model with:

  • Relaxed constraints on root node children to support well-formed external general parsed entities that are not well formed XML documents
  • An additional « base URI » property on every node.
  • An additional « unparsed entities » property on the root node.

It’s fair to say that these two -very close- data models are completely focused on XML, but is that all?

Not entirely and these two specifications introduce other notions that should be considered as related to the data model even if they are not described in their sections called « Data Model »…

XSLT 1.0 inadvertently mentions the four basic XPath data-types (string, number, boolean, node-set) to explicitly add a fifth one: result tree fragments”.

These four basic data-types are implicitly defined in XPath 1.0 in its section about its function library but no formal description of these types is given.

XDML 2.0: XPath 2.0/XSLT 2.0/XQuery 1.0

In version 2.0, the XDM is promoted to get its own specification.

XDM 2.0 keeps the same seven types of nodes as XPath 1.0 and integrates the additions from the XSLT 1.0 data model. A number of properties are added to these nodes to capture information that had been left outside the data model by the previous version and also to support the data-type system from the PSVI (Post Schema Validation Infoset).

The term « data-type » or simply « type » being now used to refer to XML Schema data-types, a new terminology is introduced where the data model is composed of « information items » (or items) being either XML nodes or « atomic values ».

The concept of « sequences » is also introduced. Sequences are not strictly considered as items but play a very important role in XDM. They are defined as an ordered collection of zero or more items”.

The data model is thus now composed of three different concepts:

  • nodes
  • atomic values
  • sequences

XDM 2.0 notes that an important difference between nodes and atomic values is that only nodes have identities:

Each node has a unique identity. Every node in an instance of the data model is unique: identical to itself, and not identical to any other node. (Atomic values do not have identity; every instance of the value “5” as an integer is identical to every other instance of the value “5” as an integer.)
XQuery 1.0 and XPath 2.0 Data Model (XDM) (Second Edition)

This is a crucial distinction that divides the data model into two different kind of items (those which have an identity and those which haven’t one). Let’s take an example:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <foo>5</foo>
    <foo>5</foo>
    <bar foo="5">
        <foo>5</foo>
    </bar>
</root>

The three <foo>5</foo> look similar and can be considered « deeply equal » but they are three different elements with three different identities. This is needed because some of their properties are different: the parent of the first two is <root/> while the parent of the third one is <bar/>, the preceding sibling of the second one is the first one while the first one has no preceeding sibling, …

The three « 5 » text nodes are similar but they still are different text nodes with different identities and this is necessary because they don’t have the same parent elements.

By contrast, the atomic values of the three <foo/> element (and the atomic value of the @foo attribute) are the same atomic value, the « 5 » (assuming they have all been declared with the same datatype). Among many other things, this means that when you manipulate their values, you can’t access back to the node that is holding the value).

XDM 3.0: XPath 3.0/XSLT 3.0/XQuery 3.0

A note Note
These specifications are still work on progress, currently divided between XQuery and XPath Data Model 3.0and data model extensions described in XSL Transformations (XSLT) Version 3.0.

XDM 3.0 adds functions as a third kind of items, transforming XQuery and XSLT into functional languages.

Like atomic values, functions have no identity:

Functions have no identity, cannot be compared, and have no serialization.
XQuery and XPath Data Model 3.0 – W3C Working Draft 13 December

2011

XSLT 3.0 adds to XDM 3.0 a fourth king of items: maps, derived from functions which, among many other use cases, can be used to model JSON objects:

Like atomic values and functions (from which they are derived), maps have no identity:

Like sequences, maps have no identity. It is meaningful to compare the contents of two maps, but there is no way of asking whether they are « the same map »: two maps with the same content are indistinguishable.
XSL Transformations (XSLT) Version 3.0 – W3C Working Draft 10 July 2012
A note Note
In this statement, the specification does acknowledge that sequences have no identity either. This is understandable but didn’t seem to be clearly specified elsewhere.

Of course, XSLT 3.0 is also adding functions to create, manipulate maps and serialize/deserialize them as JSON and a syntax to define map literals. It does not any new pattern to select of match maps or map entries, though.

Identity Crisis

Appolonius’ ship is a beautiful ship. Over the years it has been repaired so many times that there is not a single piece of the original materials remaining. The question is, therefore, is it really still Appolonius’ ship?
ObjectIdentity on c2.com

Object identity is often confused with mutability. The need for objects to have identities is more obvious when they are mutable, their identities being then used to track them despite their changes like Appolonius’ ship. However, XDM 3.0 gives us a good opportunity to explore the meaning and consequences of having (or not having) an identity for immutable object structures.

The definition of node identity in XDM 3.0 is directly copied from XDM 2.0:

Each node has a unique identity. Every node in an instance of the data model is unique: identical to itself, and not identical to any other node. (Atomic values do not have identity; every instance of the value “5” as an integer is identical to every other instance of the value “5” as an integer.)
XQuery and XPath Data Model 3.0 – W3C Working Draft 13 December 2011

I find this definition confusing:

  • Why should the value “5” as an integer be instantiated and why should we care? The value “5” as an integer is… the value “5” as an integer! It’s unique and being unique, doesn’t it have an identity?
  • A node, with all the properties defined in XDM (including its document-uri and parent accessors) would be unique if it had « previous-sibling » or « document-order » accessors.
A note Note
To find the previous siblings of a node relying only on the accessors defined in XDM (2.0 or 3.0), you’d have to access to the node’s parent and loop over it’s children until you find the current node that you would identify as such by checking its identity.

Rather than focussing on uniqueness, which for immutable information items does not really matter, a better differentiation could be between information items which have enough context information to « know where they belong » in the data model and those which don’t.

This differentiation has the benefit of highlighting the consequences of having or not having an identity: to be able to navigate between an information item and its ancestors or sibling this item must know where it belongs. When that’s not the case, it is still be possible to navigate between the item and its descendants but axis such as ancestor:: or sibling:: are not available.

A note Note
Identity can be seen as the price to pay for the ancestor:: and sibling:: axis.

Let’s take back a simple example:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <foo>5</foo>
    <foo>5</foo>
    <bar> 
        <foo>5</foo>
    </bar>
</root>

In an hypothetical data model where nodes have no identity, there would be only 3 elements:

  • The root element
  • The bar element
  • The foo element (referred twice has children of root end once as child of bar)

If we add identity (or context information) properties, the foo elements become three information different items since they defer by these properties.

The process of adding these properties to an information item looks familiar. Depending on your background, you can compare it to:

  • class/object instantiation in class based Object Oriented Programming
  • clones in prototype based Object Oriented Programming
  • RDF reification.

We’ve seen that XDM 3.0 acknowledges this difference between information items which have context information and those which don’t have. I don’t want to deny that both types of data models have their use cases: there are obviously many use cases where context information is needed and use cases where lightweight structures are a better fit.

That being said, if we are serious about the support of JSON in XDM, we should offer the same features to access data whether this data is stored in maps or in XML nodes.

Let’s consider this JSON object borrowed from the XSLT 3.0 Working Draft:

{ "accounting" : [ 
      { "firstName" : "John", 
        "lastName"  : "Doe",
        "age"       : 23 },

      { "firstName" : "Mary", 
        "lastName"  : "Smith",
        "age"       : 32 }
                 ],                                 
  "sales"     : [ 
      { "firstName" : "Sally", 
        "lastName"  : "Green",
        "age"       : 27 },

      { "firstName" : "Jim",  
        "lastName"  : "Galley",
        "age"       : 41 }
                  ]
}

This object could be represented in XML by the following document:

<?xml version="1.0" encoding="UTF-8"?>
<company>
    <department name="sales">
        <employee>
            <firstName>Sally</firstName>
            <lastName>Green</lastName>
            <age>27</age>
        </employee>
        <employee>
            <firstName>Jim</firstName>
            <lastName>Galley</lastName>
            <age>41</age>
        </employee>
    </department>
    <department name="accounting">
        <employee>
            <firstName>John</firstName>
            <lastName>Doe</lastName>
            <age>23</age>
        </employee>
        <employee>
            <firstName>Mary</firstName>
            <lastName>Smith</lastName>
            <age>32</age>
        </employee>
    </department>
</company>

The features introduced in the latest XSLT 3.0 Working Draft do allow to transform rather easily from one model to the other, but these two models do not have, bar far, the same features.

In the XML flavor, when the context item is the employee « John Doe », you can easily find out what his department is because this is an element and element do carry context information.

In the map flavor by contrast when the context item is an employee map, this object has no context information and you can’t tell which is his department without looping within the containing map.

This important restriction is at a purely data model level. It is aggravated by the XPath syntax has not been extended to generalize axis so that they can work with maps. If I work with the XML version of this structure, it’s obvious to evaluate things such as the number of employees, the average age of employees, the number of departments, the number of employees by department, the average age by department, obvious to find out if there is an employee called « Mary Smith » in one of the departments, the employees who are more than 40, to get a list of employees from all the department sorted by age, … In the map flavor by contrast, I don’t have any XPath axis available and must do all these operations using a limited number of map functions (map:keys(), map:contains(), map:get()). In other words, while I can use XPath expressions with the XML version, I must use DOM like operations to access the map version!

To summarize, yes XDM 3.0 does support JSON but to do pretty much anything interesting with JSON objects, you’d better transform them into XML nodes first! XSLT 3.0 does give you the tools to do this transformation quite easily but the message to JSON users is that we don’t treat their data model as a first class citizen.

To make it worse, XPath is used by many other specifications, within and outside the W3C and the level of support for JSON provided by XDM and XPath will determine how these specifications will be able to support for JSON. Specifications that are impacted by this issue include XForms, XProc and Schematron. Supporting JSON would be really useful for these three specifications if and only if map items could have the same features than nodes.

Furthermore, the same asymmetry exists when you went to create these two structures from other sources: to create the XML structure you can use sequence constructors but to create the map structure, you have to use the map:new() and map:item() functions.

My proposal to solve this issue is:

  • To acknowledge the fact that any type of information item can be either « context independent » or include context information and explore the consequences of thisstatement.
  • To generalize XPath axis so that they can be used with map items.
  • To create sequence constructors for maps and map entries.

You are welcome to discuss this further:

Introducing χίμαιραλ (chimeral), the Chimera Language

When I started to work on χίμαιραλ a few months ago, my first motivation was to propose an XDM serialization for maps which would turn the rather abstract prose from the specification into concrete angle brackets that you could see and read.

The exercise has been very instructive and helped me a lot to understand the spec, however a more ambitious use pattern has emerged while I was making progress. The XSLT 3.0 Working Draft is part of a batch of Working Drafts which are far more advanced. My proposals to solve the « map identity crisis » are probably too intrusive and too late to be taken into account and the batch of specifications will most probably carry on with the current proposal.

If that’s the case, we’ve seen that it makes a lot of sense to convert maps into nodes to enable to use XPath axis and χίμαιραλ provides a generic target format for these conversions.

Example

Let’s take again the JSON object borrowed from the XSLT 3.0 Working Draft:

{ "accounting" : [ 
      { "firstName" : "John", 
        "lastName"  : "Doe",
        "age"       : 23 },

      { "firstName" : "Mary", 
        "lastName"  : "Smith",
        "age"       : 32 }
                 ],                                 
  "sales"     : [ 
      { "firstName" : "Sally", 
        "lastName"  : "Green",
        "age"       : 27 },

      { "firstName" : "Jim",  
        "lastName"  : "Galley",
        "age"       : 41 }
                  ]
}

Its χίμαιραλ representation is:

<?xml version="1.0" encoding="UTF-8"?>
<χ:data-model xmlns:χ="http://χίμαιραλ.com#">
    <χ:map>
        <χ:entry key="sales" keyType="string">
            <χ:map>
                <χ:entry key="1" keyType="number">
                    <χ:map>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Green</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">27</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">Sally</χ:atomic-value>
                        </χ:entry>
                    </χ:map>
                </χ:entry>
                <χ:entry key="2" keyType="number">
                    <χ:map>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Galley</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">41</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">Jim</χ:atomic-value>
                        </χ:entry>
                    </χ:map>
                </χ:entry>
            </χ:map>
        </χ:entry>
        <χ:entry key="accounting" keyType="string">
            <χ:map>
                <χ:entry key="1" keyType="number">
                    <χ:map>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Doe</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">23</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">John</χ:atomic-value>
                        </χ:entry>
                    </χ:map>
                </χ:entry>
                <χ:entry key="2" keyType="number">
                    <χ:map>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Smith</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">32</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">Mary</χ:atomic-value>
                        </χ:entry>
                    </χ:map>
                </χ:entry>
            </χ:map>
        </χ:entry>
    </χ:map>
</χ:data-model>

Granted, it’s much more verbose than the JSON version, but it’s the exact translation of the XDM corresponding to the JSON object in XML.

χίμαιραλ In a Nutshell

The design goals are:

  • Be as close as possible to the XDM and its terminology
  • Represent XML nodes as… XML nodes
  • Allow round-trips (an XDM model serialized as χίμαιραλ should give a XDM model identical to the original one when de-serialized)
  • Be easy to process using XPath/XQuery/XSLT
  • Support of the PSVI is not a goal

χίμαιραλ is not the only proposal to serialize XDM as XML. Two other notable ones are:

  • Zorba’s XDM serializationis a straight andaccurate XDM serialization which does support PSVI annotations. As a consequence, nodes are serialized as xdm:*elements (an element is anxdm:element, an attribute an xdm:attribute element, …). This does’n meet by second requirement to represent nodes as themselves.
  • XDML, presented by Rennau, Hans-Jürgen, and David A. Lee atBalisage 2011 is more than just an XDM serialization and also includes manipulation and processing definitions. It introduces its own terminology and concepts and is toofar away from XDM for my design goals.

A lot of attention has been given to the first design goal: the structure of a χίμαιραλ model and the name of its elements and attributes are directly derived from the specifications.

In XDM, map entries’ values can be arrays (an array beeing nothing else than a map with integer keys) but also sequences (which is not possible in JSON). χίμαιραλ respects the fact that in XDM there is no difference between a sequence composed of a single element and represents sequences by a repetition of values.

The map map{1:= 'foo'} is serialized as:

<χ:data-model xmlns:χ="http://χίμαιραλ.com#">
   <χ:map>
      <χ:entry key="1" keyType="number">
         <χ:atomic-value type="string">foo</χ:atomic-value>
      </χ:entry>
   </χ:map>
</χ:data-model>

And the map map{1:= ('foo', 'bar')} is serialized as:

<χ:data-model xmlns:χ="http://χίμαιραλ.com#">
   <χ:map>
      <χ:entry key="1" keyType="number">
         <χ:atomic-value type="string">foo</χ:atomic-value>
         <χ:atomic-value type="string">bar</χ:atomic-value>
      </χ:entry>
   </χ:map>
</χ:data-model>

We’ve seen that XDM makes a clear distinction between nodes which have identities and other item types (atomic values, functions and maps) which haven’t. XDM allows to use nodes as map entry values. χίμαιραλ allows this feature too, but copying the nodes would create new nodes with different identities.

To avoid that, documents to which these nodes belong are copied into χ:instance elements and references between map entries values and instances are made using XPath expressions.

The following $map variable:

<xsl:variable name="a-node">
    <foo/>
</xsl:variable>
<xsl:variable name="map" select="map{'a-node':= $a-node}"/>

Is serialized as:

<χ:data-model xmlns:χ="http://χίμαιραλ.com#">
   <χ:instance id="d4" kind="document">
      <foo/>
   </χ:instance>
   <χ:map>
      <χ:entry key="a-node" keyType="string">
         <χ:node kind="document" instance="d4" path="/"/>
      </χ:entry>
   </χ:map>
</χ:data-model>

Like XSLT variable, instances do not always contain document nodes and the following $map variable:

<xsl:variable name="a-node" as="node()">
    <foo/>
</xsl:variable>
<xsl:variable name="map" select="map{'a-node':= $a-node}"/>

Is serialized as:

<χ:data-model xmlns:χ="http://χίμαιραλ.com#">
   <χ:instance id="d4e0" kind="fragment">
      <foo/>
   </χ:instance>
   <χ:map>
      <χ:entry key="a-node" keyType="string">
         <χ:node kind="element" instance="d4e0" path="root()" name="foo"/>
      </χ:entry>
   </χ:map>
</χ:data-model>

Nodes can belong to more than one instances, and this $map variable:

<xsl:variable name="a-node" as="node()*">
    <foo/>
    <bar/>
</xsl:variable>
<xsl:variable name="map" select="map{'a-node':= $a-node}"/>

Is serialized as:

<χ:data-model xmlns:χ="http://χίμαιραλ.com#">
   <χ:instance id="d4e0" kind="fragment">
      <foo/>
   </χ:instance>
   <χ:instance id="d4e3" kind="fragment">
      <bar/>
   </χ:instance>
   <χ:map>
      <χ:entry key="a-node" keyType="string">
         <χ:node kind="element" instance="d4e0" path="root()" name="foo"/>
         <χ:node kind="element" instance="d4e3" path="root()" name="bar"/>
      </χ:entry>
   </χ:map>
</χ:data-model>

Nodes can be « deep linked », a same node can be linked several times and nodes can be mixed with atomic values at wish. The following $map variable:

<xsl:variable name="doc">
    <department name="sales">
        <employee>
            <firstName>Sally</firstName>
            <lastName>Green</lastName>
            <age>27</age>
        </employee>
        <employee>
            <firstName>Jim</firstName>
            <lastName>Galley</lastName>
            <age>41</age>
        </employee>
    </department>
    <department name="accounting">
        <employee>
            <firstName>John</firstName>
            <lastName>Doe</lastName>
            <age>23</age>
        </employee>
        <employee>
            <firstName>Mary</firstName>
            <lastName>Smith</lastName>
            <age>32</age>
        </employee>
    </department>
</xsl:variable>
<xsl:variable name="map"
    select="map{
            'sales' := $doc/department[@name='sales'],
            'Sally' := $doc//employee[firstName = 'Sally'],
            'kids'  := $doc//employee[age &lt; 30],
            'dep-names-attributes' := $doc/department/@name,
            'dep-names' := for $name in $doc/department/@name return string($name)
            }"/>

Is serialized as:

<χ:data-model xmlns:χ="http://χίμαιραλ.com#">
   <χ:instance id="d4" kind="document">
      <department name="sales">
         <employee>
            <firstName>Sally</firstName>
            <lastName>Green</lastName>
            <age>27</age>
         </employee>
         <employee>
            <firstName>Jim</firstName>
            <lastName>Galley</lastName>
            <age>41</age>
         </employee>
      </department>
      <department name="accounting">
         <employee>
            <firstName>John</firstName>
            <lastName>Doe</lastName>
            <age>23</age>
         </employee>
         <employee>
            <firstName>Mary</firstName>
            <lastName>Smith</lastName>
            <age>32</age>
         </employee>
      </department>
   </χ:instance>
   <χ:map>
      <χ:entry key="sales" keyType="string">
         <χ:node kind="element"
                 instance="d4"
                 path="/&#34;&#34;:department[1]"
                 name="department"/>
      </χ:entry>
      <χ:entry key="Sally" keyType="string">
         <χ:node kind="element"
                 instance="d4"
                 path="/&#34;&#34;:department[1]/&#34;&#34;:employee[1]"
                 name="employee"/>
      </χ:entry>
      <χ:entry key="kids" keyType="string">
         <χ:node kind="element"
                 instance="d4"
                 path="/&#34;&#34;:department[1]/&#34;&#34;:employee[1]"
                 name="employee"/>
         <χ:node kind="element"
                 instance="d4"
                 path="/&#34;&#34;:department[2]/&#34;&#34;:employee[1]"
                 name="employee"/>
      </χ:entry>
      <χ:entry key="dep-names-attributes" keyType="string">
         <χ:node kind="attribute"
                 instance="d4"
                 path="/&#34;&#34;:department[1]/@name"
                 name="name">sales</χ:node>
         <χ:node kind="attribute"
                 instance="d4"
                 path="/&#34;&#34;:department[2]/@name"
                 name="name">accounting</χ:node>
      </χ:entry>
      <χ:entry key="dep-names" keyType="string">
         <χ:atomic-value type="string">sales</χ:atomic-value>
         <χ:atomic-value type="string">accounting</χ:atomic-value>
      </χ:entry>
   </χ:map>
</χ:data-model>

Remaining Issues

A collation property should be added to <χ:map/>, probably as an attribute, the transformation to serialize to χίμαιραλ should be cleaned up and the reverse transformation should be implemented.

These are pretty trivial issues and the biggest one is probably to find a way to cleanly serialize references to nodes that are not contained within an element, such as the following $map variable:

<xsl:variable name="attribute" as="node()">
    <xsl:attribute name="foo">bar</xsl:attribute>
</xsl:variable>
<xsl:variable name="map"
    select="map{
            'attribute' := $attribute
            }"/>

Support of functions should also be considered.

χίμαιραλ and the identity crisis

To some extend, χίμαιραλ can be considered as a solution to the XDM identity crisis:

  • Serializing an XDM model as χίμαιραλ creates elements for maps, map entries and atomic values and these elements, being nodes, have identities. The serialization istherefore also an instantiation of XDM information items as defined above.
  • De-serializing a χίμαιραλ to create an XDM data model is also a de-instantiation– except of course that the identity of XML nodes is not « removed ».

However, χίμαιραλ does keep a strong difference between nodes which are kept in <χ:instance> elements and maps and atomic values.

Moving the chimera forward

χίμαιραλ is a good playground to explore the new possibilities offered by XDM 3.0. Here is a (non exhaustive) list of a few directions that seem interesting…

A note Note
Don’t expect to find fully baked proposals in this section which contains, on the contrary very early drafts of ideas to follow to support XDM maps as « first class citizens »!

Embracing RDF

If you had the opportunity to enjoy the sunny weather of Orlando in December 2001, you may remember « The Syntactic Web » a provocative talk where Jonathan Robie has shown how XQuery 1.0 could be used to query normalized XML/RDF documents.

The gap between RDF triples and the versatility of its XML representation was a big issue, but the new features brought by this new version of the XPath/XQuery/XSLT package should help us.

The basic data model of RDF is based on triples, a triple being a composed of a subject, a predicate and an object. In XDM, a triple can now be represented by either a sequence, an array or a map of three items.

XDM sequences have the property that they cannot include other sequences and representing triples as sequences would mean that you couldn’t define sequences of triples. For that reason it is probably better to define triples as maps or arrays. An array being a map indexed by integers, that doesn’t make a huge difference at a conceptual level, but I find it cleaner to access to the subject of a triple using a QName (such as rdf:subject) rather than an index. Following this principle, we could define a triple as:

map {
    xs:QName('rdf:subject')   := xs:anyURI('http://www.example.org/index.html'),
    xs:QName('rdf:predicate') := xs:anyURI('http://purl.org/dc/elements/1.1/creator'),
    xs:QName('rdf:object')    := xs:anyURI('http://www.example.org/staffid/85740')
}

The χίμαιραλ serialization of this map is:

<χ:data-model xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:χ="http://χίμαιραλ.com#"
              xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
   <χ:map>
      <χ:entry key="rdf:object"
               keyType="xs:QName">
         <χ:atomic-value type="xs:anyURI">http://www.example.org/staffid/85740</χ:atomic-value>
      </χ:entry>
      <χ:entry key="rdf:predicate"
               keyType="xs:QName">
         <χ:atomic-value type="xs:anyURI">http://purl.org/dc/elements/1.1/creator</χ:atomic-value>
      </χ:entry>
      <χ:entry key="rdf:subject"
               keyType="xs:QName">
         <χ:atomic-value type="xs:anyURI">http://www.example.org/index.html</χ:atomic-value>
      </χ:entry>
   </χ:map>
</χ:data-model>

What can we do with such triples? Using higher order functions, it should not be too difficult to define triple stores with basic query features!

Is this lightweight enough? Or does RDF support deserve new information item types to be supported by XDM?

Syntactical sugar

We’ve seen that this JSON object

{ "accounting" : [ 
      { "firstName" : "John", 
        "lastName"  : "Doe",
        "age"       : 23 },

      { "firstName" : "Mary", 
        "lastName"  : "Smith",
        "age"       : 32 }
                 ],                                 
  "sales"     : [ 
      { "firstName" : "Sally", 
        "lastName"  : "Green",
        "age"       : 27 },

      { "firstName" : "Jim",  
        "lastName"  : "Galley",
        "age"       : 41 }
                  ]
}

Is serialized in χίμαιραλ as:

<?xml version="1.0" encoding="UTF-8"?>
<χ:data-model xmlns:χ="http://χίμαιραλ.com#">
    <χ:map>
        <χ:entry key="sales" keyType="string">
            <χ:map>
                <χ:entry key="1" keyType="number">
                    <χ:map>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Green</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">27</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">Sally</χ:atomic-value>
                        </χ:entry>
                    </χ:map>
                </χ:entry>
                <χ:entry key="2" keyType="number">
                    <χ:map>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Galley</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">41</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">Jim</χ:atomic-value>
                        </χ:entry>
                    </χ:map>
                </χ:entry>
            </χ:map>
        </χ:entry>
        <χ:entry key="accounting" keyType="string">
            <χ:map>
                <χ:entry key="1" keyType="number">
                    <χ:map>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Doe</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">23</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">John</χ:atomic-value>
                        </χ:entry>
                    </χ:map>
                </χ:entry>
                <χ:entry key="2" keyType="number">
                    <χ:map>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Smith</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">32</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">Mary</χ:atomic-value>
                        </χ:entry>
                    </χ:map>
                </χ:entry>
            </χ:map>
        </χ:entry>
    </χ:map>
</χ:data-model>

We can work with that, but wouldn’t it be nice if we had a native syntax that does not use XML elements and attributes to represent maps?

Depending on the requirements, many approaches are possible.

A first option would be to define pluggable notation parsers within XML and write:

<χ:notation mediatype="application/json"><![CDATA[
{ "accounting" : [ 
      { "firstName" : "John", 
        "lastName"  : "Doe",
        "age"       : 23 },

      { "firstName" : "Mary", 
        "lastName"  : "Smith",
        "age"       : 32 }
                 ],                                 
  "sales"     : [ 
      { "firstName" : "Sally", 
        "lastName"  : "Green",
        "age"       : 27 },

      { "firstName" : "Jim",  
        "lastName"  : "Galley",
        "age"       : 41 }
                  ]
}                  
]]></χ:notation>

The meaning of the <χ:notation/> element would be to trigger a parser supporting the application/json datatype. This is less verbose, more natural to JSON users, but doesn’t allow to add XML nodes in maps or sequences.

Another direction would be to extend the syntax of XML itself. To do so, again, there are many possibilities. The markup in XML is based on angle brackets and the distinction between the different XML productions is usually done through the character following the bracket in the opening tags.

This principle leaves a lot of possibilities. For instance, maps could be identified by the tags <{> and </}> to follow the characters used by XDM map literals and JSON objects:

<χ:data-model>
    <{>
        <χ:entry key="sales" keyType="string">
            <{>
                <χ:entry key="1" keyType="number">
                    <{>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Green</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">27</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">Sally</χ:atomic-value>
                        </χ:entry>
                    </}>
                </χ:entry>
                <χ:entry key="2" keyType="number">
                    <{>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Galley</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">41</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">Jim</χ:atomic-value>
                        </χ:entry>
                    </}>
                </χ:entry>
            </}>
        </χ:entry>
        <χ:entry key="accounting" keyType="string">
            <{>
                <χ:entry key="1" keyType="number">
                    <{>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Doe</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">23</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">John</χ:atomic-value>
                        </χ:entry>
                    </}>
                </χ:entry>
                <χ:entry key="2" keyType="number">
                    <{>
                        <χ:entry key="lastName" keyType="string">
                            <χ:atomic-value type="string">Smith</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="age" keyType="string">
                            <χ:atomic-value type="number">32</χ:atomic-value>
                        </χ:entry>
                        <χ:entry key="firstName" keyType="string">
                            <χ:atomic-value type="string">Mary</χ:atomic-value>
                        </χ:entry>
                    </}>
                </χ:entry>
            </}>
        </χ:entry>
    </}>
</χ:data-model>

Map entries are not ordered and in that respect they are similar to XML attributes. We could use this similarity and use the character @ to identify map entries:

<χ:data-model>
    <{>
        <@"sales" keyType="string">
            <{>
                <@"1" keyType="number">
                    <{>
                        <@"lastName" keyType="string">
                            <χ:atomic-value type="string">Green</χ:atomic-value>
                        </@"lastName">
                        <@"age" keyType="string">
                            <χ:atomic-value type="number">27</χ:atomic-value>
                        </@"age">
                        <@"firstName" keyType="string">
                            <χ:atomic-value type="string">Sally</χ:atomic-value>
                        </@"firstName">
                    </}>
                </@"1">
                <@"2" keyType="number">
                    <{>
                        <@"lastName" keyType="string">
                            <χ:atomic-value type="string">Galley</χ:atomic-value>
                        </@"lastName">
                        <@"age" keyType="string">
                            <χ:atomic-value type="number">41</χ:atomic-value>
                        </@"age">
                        <@"firstName" keyType="string">
                            <χ:atomic-value type="string">Jim</χ:atomic-value>
                        </@"firstName">
                    </}>
                </@"2">
            </}>
        </@"sales">
        <@"accounting" keyType="string">
            <{>
                <@"1" keyType="number">
                    <{>
                        <@"lastName" keyType="string">
                            <χ:atomic-value type="string">Doe</χ:atomic-value>
                        </@"lastName">
                        <@"age" keyType="string">
                            <χ:atomic-value type="number">23</χ:atomic-value>
                        </@"age">
                        <@"firstName" keyType="string">
                            <χ:atomic-value type="string">John</χ:atomic-value>
                        </@"firstName">
                    </}>
                </@"1">
                <@"2" keyType="number">
                    <{>
                        <@"lastName" keyType="string">
                            <χ:atomic-value type="string">Smith</χ:atomic-value>
                        </@"lastName">
                        <@"age" keyType="string">
                            <χ:atomic-value type="number">32</χ:atomic-value>
                        </@"age">
                        <@"firstName" keyType="string">
                            <χ:atomic-value type="string">Mary</χ:atomic-value>
                        </@"firstName">
                    </}>
                </@"2">
            </}>
        </@"accounting">
    </}>
</χ:data-model>

The key names have been enclosed between quotes because map keys can include any character including whitespaces, but they can be made optional when they are not needed. We could also give to the keyType a default value of « string »:

<χ:data-model>
    <{>
        <@sales>
            <{>
                <@1 keyType="number">
                    <{>
                        <@lastName>
                            <χ:atomic-value type="string">Green</χ:atomic-value>
                        </@lastName
                        <@age>
                            <χ:atomic-value type="number">27</χ:atomic-value>
                        </@age
                        <@firstName>
                            <χ:atomic-value type="string">Sally</χ:atomic-value>
                        </@firstName
                    </}>
                </@1
                <@2 keyType="number">
                    <{>
                        <@lastName>
                            <χ:atomic-value type="string">Galley</χ:atomic-value>
                        </@lastName
                        <@age>
                            <χ:atomic-value type="number">41</χ:atomic-value>
                        </@age
                        <@firstName>
                            <χ:atomic-value type="string">Jim</χ:atomic-value>
                        </@firstName
                    </}>
                </@2
            </}>
        </@sales
        <@accounting>
            <{>
                <@1 keyType="number">
                    <{>
                        <@lastName>
                            <χ:atomic-value type="string">Doe</χ:atomic-value>
                        </@lastName
                        <@age>
                            <χ:atomic-value type="number">23</χ:atomic-value>
                        </@age
                        <@firstName>
                            <χ:atomic-value type="string">John</χ:atomic-value>
                        </@firstName
                    </}>
                </@1
                <@2 keyType="number">
                    <{>
                        <@lastName>
                            <χ:atomic-value type="string">Smith</χ:atomic-value>
                        </@lastName
                        <@age>
                            <χ:atomic-value type="number">32</χ:atomic-value>
                        </@age
                        <@firstName>
                            <χ:atomic-value type="string">Mary</χ:atomic-value>
                        </@firstName
                    </}>
                </@2
            </}>
        </@accounting
    </}>
</χ:data-model>

Atomic values could be identified by <=> and </=> and the same default value applied to its type attribute:

<χ:data-model>
    <{>
        <@sales>
            <{>
                <@1 keyType="number">
                    <{>
                        <@lastName>
                            <=>Green</=>
                        </@lastName>
                        <@age>
                            <= type="number">27</=>
                        </@age>
                        <@firstName>
                            <=>Sally</=>
                        </@firstName>
                    </}>
                </@1>
                <@2 keyType="number">
                    <{>
                        <@lastName>
                            <=>Galley</=>
                        </@lastName>
                        <@age>
                            <= type="number">41</=>
                        </@age>
                        <@firstName>
                            <=>Jim</=>
                        </@firstName>
                    </}>
                </@2>
            </}>
        </@sales>
        <@accounting>
            <{>
                <@1 keyType="number">
                    <{>
                        <@lastName>
                            <=>Doe</=>
                        </@lastName>
                        <@age>
                            <= type="number">23</=>
                        </@age>
                        <@firstName>
                            <=>John</=>
                        </@firstName>
                    </}>
                </@1>
                <@2 keyType="number">
                    <{>
                        <@lastName>
                            <=>Smith</=>
                        </@lastName>
                        <@age>
                            <= type="number">32</=>
                        </@age>
                        <@firstName>
                            <=>Mary</=>
                        </@firstName>
                    </}>
                </@2>
            </}>
        </@accounting>
    </}>
</χ:data-model>

The tags that surround atomic values are useful when these values are within a sequence but look superfluous when the item has a single value. The next step could be to define that in that case as a shortcut the value and its type attribute could be directly included in the item:

<χ:data-model>
    <{>
        <@sales>
            <{>
                <@1 keyType="number">
                    <{>
                        <@lastName>Green</@lastName>
                        <@age type="number">27</@age>
                        <@firstName>Sally</@firstName>
                    </}>
                </@1>
                <@2 keyType="number">
                    <{>
                        <@lastName>Galley</@lastName>
                        <@age type="number">41</@age>
                        <@firstName>Jim</@firstName>
                    </}>
                </@2>
            </}>
        </@sales>
        <@accounting>
            <{>
                <@1 keyType="number">
                    <{>
                        <@lastName>Doe</@lastName>
                        <@age type="number">23</@age>
                        <@firstName>John</@firstName>
                    </}>
                </@1>
                <@2 keyType="number">
                    <{>
                        <@lastName>Smith</@lastName>
                        <@age type="number">32</@age>
                        <@firstName>Mary</@firstName>
                    </}>
                </@2>
            </}>
        </@accounting>
    </}>
</χ:data-model>

XPath

The χίμαιραλ serialization being XML, it is possible to use XPath path expressions to query its structure. For instance, to get a list of employees which are less than 30, we can

write:

χ:map/χ:entry/χ:map/χ:entry/χ:map[χ:entry[@key='age'][χ:atomic-value < 30]]

Or, if we’re feeling lucky:

//χ:map[χ:entry[@key='age'][χ:atomic-value < 30]]

Again, that’s good as long we work on a χίμαιραλ serialization but it would be good to be able to use path expressions directly on map data structures. To do so we would need at minima to define steps to match maps and entries.

XSLT 3.0 introduces a new map() item type which could be used as a kind test to identify maps.

If we follow the idea that map entries are similar to XML attributes, we could use the @ notation to identify them. The XPath expression would then become:

map()/@*/map()/@*/map()[@age < 30]]

Or, if we’re feeling lucky:

//map()[@age < 30]]

Validation

These data models can be complex. Wouldn’t it be useful to be able to validate them with schema languages? This would give us a way to validate JSON maps!

Of course we can already serialize them in χίμαιραλ and validate the serialization using any schema language, but again it would be good to be able to validate these structures directly.

A RELAX NG schema to validate the χίμαιραλ serialization of our example would be:

namespace χ = "http://χίμαιραλ.com#"

start = element χ:data-model { top-level-map }

# Top level map: departments
top-level-map =
    element χ:map {
        element χ:entry {
            attribute key { xsd:NMTOKEN },
            attribute keyType { "string" },
            emp-array
        }*
    }

# List of employees
emp-array =
    element χ:map {
        element χ:entry {
            attribute key { xsd:positiveInteger },
            attribute keyType { "number" },
            emp-map
        }*
    }

# Description of an employee
emp-map = element χ:map { (age | firstName | lastName) + }

age =
    element χ:entry {
        attribute key { "age" },
        attribute keyType { "string" },
        element χ:atomic-value {
            attribute type { "number" },
            xsd:positiveInteger
        }
    }

firstName =
    element χ:entry {
        attribute key { "firstName" },
        attribute keyType { "string" },
        element χ:atomic-value {
            attribute type { "string" },
            xsd:token
        }
    }

lastName =
    element χ:entry {
        attribute key { "lastName" },
        attribute keyType { "string" },
        element χ:atomic-value {
            attribute type { "string" },
            xsd:token
        }
    }
A note Note
In the description of the maps used to describe employees, we cannot use interleave patterns because of the restriction on interleave and the schema is approximate. In this specific case, we could

enumerate the six possible combinations but the exercise would quickly become verbose if the number of items

grew:

emp-map = element χ:map { 
      (age, firstName, lastName)  
    | (age, lastName, firstName) 
    | (firstName, age, lastName)  
    | (firstName, lastName, age) 
    | (lastName, age, firstName)  
    | (lastName, firstName, age) 
}

A Schematron schema for the χίμαιραλ serialization could be developed based on XPath expressions similar to those that have been shown in the previous section.

Again, it would be interesting to support maps directly as first class citizens in XML schema languages.

The ability to use Schematron on XDM maps depends directly on the ability to browse maps using patterns and path expressions in XPath and XSLT (see above)…

The main impact on RELAX NG would be to add map and item patterns and the schema could look like:

namespace χ = "http://χίμαιραλ.com#"

start = element χ:data-model { top-level-map }

# Top level map: departments
top-level-map =
    map  {
        entry xsd:NMTOKEN {
            emp-array
        }*
    }

# List of employees
emp-array =
    map {
        entry xsd:positiveInteger {
            emp-map
        }*
    }

# Description of an employee
emp-map = map { age, firstName, lastName  }

age =
    entry age {
            xsd:positiveInteger
        }
    }

firstName =
    entry firstName {
             xsd:token
        }
    }

lastName =
    entry lastName {
            xsd:token
        }
    }

Sequences could probably be supported without adding a new pattern but would require to relax some restrictions to allow the description of sequences mixing atomic values, maps and nodes (in Relax NG, sequences of atomic values are already possible in list datatypes, sequences of nodes are of course available to describe node contents but these two type of sequences cannot be mixed).

Conclusion

According to the definition of chimeras in genetics from Wikipedia quoted in the introduction, [chimeras are formed from at least four parent cells (two fertilized eggs or early embryos fused together). Each population of cells keeps its own character and the resulting organism is a mixture of tissues].

The current XDM proposals have added to the XML data model a foreign model to represent maps. This new model is a superset of the JSON data model. The two data models keep their own character and the resulting model is a mixture of information items.

It’s far to say that the current XDM proposal is a chimera, something described as [usually ugly, foolish or impossible fantasies] by Jeni Tennison.

I hope that the proposals sketched in this paper will help to address this situation and fully integrate these new information items in the XML echosystem.

Test driven XML development

Can test driven development be applied to XML technologies? to XSLT? to XML schema languages? XML pipelines?

This is the topic of the poster I am presenting this year at the Balisage conference.

For those of you who are not lucky enough to attend, here is a copy of this poster: Test driven development in XML Balisage 2012 poster

Schema test driven development

Note: this article is derived from the presentation I have given at the International Symposium on Quality Assurance and Quality Control in XML (precedings).

Abstract

Ever modified an XML schema? Ever broken something while fixing a bug or adding a new feature? As withany piece of engineering, the more complex a schema is, the harder it is to maintain. In other domains, unit tests dramatically reduce the number of regressions and thus provide a kind of safety net for maintainers. Can we learn from these techniques and adapt them to XML schema languages? In this workshop session, we develop a schema using unit test techniques, to illustrate their benefits in this domain.


The workshop is run as an exchange between a customer (played by Tommie Usdin) and a schema expert (played by Eric van der Vlist).

The customer, needs a schema for her to list XML application, is puzzled by the « test first programming » technique imposed by the schema expert.

At the end of the day (or workshop), will she be converted to this well known agile or extreme programming technique adapted to the development of XML schemas?

Step 1: Getting started

Hi Eric, can you help me to write a schema?
Customer
Hi Tommie, yes, sure, what will the schema be about?
Expert
I need a vocabulary for my todo lists, with todo ite…
Customer
OK, you’ve told me enough, let’s get started
Expert (interrupting his customer)
Get started? but I haven’t told you anything about it!
Customer
Right, but it’s never too soon to write tests when you do test first programming!
Expert
A note Note
Test first programming (also called test driven development) developers create test case (usually unit test cases) before implementing a function. The test suite is run, code is written based on the result of these tests and the test suite and code are updated untill all the tests pass.

Test suite

(suite.xml):

<tf:suite xmlns:tf="http://xmlschemata.org/test-first/" xmlns:todo="http://balisage.net/todo#" title="Basic tests">
    <tf:case title="Root element" expected="valid" id="root">
        <todo:list/>
    </tf:case>
</tf:suite>
A note Note
The vocabulary used to define these test cases has been inspired by the SUT (XML Schema Unit Test) project. It’s a simple vocabulary (composed of only three different element) allowing to pack several XML instances together with the outcome validation result. It uses conventions that you’ll discover during the course of this workshop.

Figure 1. Test results

Test results

Test results

 

A note Note
The test suite is run using a simple Orbeon Forms application. The rendering relies on Orbeon Forms XForms’ implementation while the test suite is run using an Orbeon Forms’ XPLpipeline.

Step 2: Adding a schema

You see, you can already write todo lists!
Expert
Hold on, we don’t have any schema!
Customer
That’s true, but you don’t have to write a schema to write XML documents.
Expert
I know, but you’re here to write a schema! Furthermore right now we accept anything. I don’t want

to have XML documents with anything as a root element!

Customer
That’s a good reason to write a schema but before that we need to add a test in our suite

first.

Expert

Test suite

(suite.xml):

<?xml version="1.0" encoding="UTF-8"?>
<tf:suite xmlns:tf="http://xmlschemata.org/test-first/" xmlns:todo="http://balisage.net/todo#" title="Basic tests">
    <tf:case title="TODO list toot element" expected="valid" id="root">
        <todo:list/>
    </tf:case>
    <tf:case title="Other root element" expected="error" id="other-root">
        <todo:title>A title</todo:title>
    </tf:case>
</tf:suite>
Now that we’ve updated the test suite, we run it again.
Expert

Figure 2. Test results

Test results

Test results

 

This result was expected and we can now proceed to create a schema and attach it to the test suite.
Expert
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    targetNamespace="http://balisage.net/todo#"
    xmlns="http://balisage.net/todo#">

    <xs:element
        name="list"/>
</xs:schema>

todo.xsd

<?xml version="1.0" encoding="UTF-8"?>
<tf:suite
    xmlns:tf="http://xmlschemata.org/test-first/"
    xmlns:todo="http://balisage.net/todo#"
    title="Basic tests">
    <tf:validation
        href="todo.xsd"
        type="xsd"/>
    <tf:case
        title="TODO list toot element"
        expected="valid"
        id="root">
        <todo:list/>
    </tf:case>
    <tf:case
        title="Other root element"
        expected="error"
        id="other-root">
        <todo:title>A title</todo:title>
    </tf:case>
</tf:suite>

suite.xml

It’s time to test again what we’ve done.
Expert

Figure 3. Test results

Test results

Test results

 

Step 3: Adding list title elements

I am happy to see some progress, at last, but I don’t want to accept any content in the todo list element. Can you add list title elements?
Customer
Sure, back to the test suite…
Expert

Test suite

(suite.xml):

<?xml version="1.0" encoding="UTF-8"?>
<tf:suite
    xmlns:tf="http://xmlschemata.org/test-first/"
    xmlns:todo="http://balisage.net/todo#"
    title="Basic tests">
    <tf:validation
        href="todo.xsd"
        type="xsd"/>
    <tf:case
        title="TODO list root element"
        expected="valid"
        id="root">
        <todo:list/>
    </tf:case>
    <tf:case
        title="TODO list with a title"
        expected="valid"
        id="list-title">
        <todo:list>
            <todo:title/>
        </todo:list>
    </tf:case>
    <tf:case
        title="Other root element"
        expected="error"
        id="other-root">
        <todo:title>A title</todo:title>
    </tf:case>
</tf:suite>
Now that we’ve updated the test suite, we run it again.
Expert

Figure 4. Test results

Test results

Test results

 

You see? We do already support list title elements!
Expert
Sure, but I don’t want to accept any content in my todo list. And the title element should be mandatory. And it should not be empty by have at least one character!
Customer
Back to the test suite, then…
Expert

Test suite

(suite.xml):

<?xml version="1.0" encoding="UTF-8"?>
<tf:suite
    xmlns:tf="http://xmlschemata.org/test-first/"
    xmlns:todo="http://balisage.net/todo#"
    title="Basic tests">
    <tf:validation
        href="todo.xsd"
        type="xsd"/>
    <todo:list>
        <tf:case
            title="Empty list element"
            expected="error"
            id="root-empty"/> 
        <todo:title>
            <tf:case title="empty title" expected="error" id="empty-title"/>
            <tf:case title="non empty title" expected="valid" id="non-empty-title">A title</tf:case>
        </todo:title>
        <tf:case
            title="Un expected element"
            expected="error"
            id="unexpected">
            <todo:foo/>
        </tf:case>
    </todo:list>
    <tf:case
        title="Other root element"
        expected="error"
        id="other-root">
        <todo:title>A title</todo:title>
    </tf:case>
</tf:suite>
A note Note
This is the first example with non top level tf:case elements. To understand how this works, we must look in more detail to the algorithm used by the framework to split a test suite into instances. The algorithm consists in two steps:

  • Loop over each tf:case element
  • Suppression of the tf:caseelements and of the top level elements which arenot ancestors of the current tf:case element.

This description may look complex, but the result is a rather intuitive way to define sub-trees that are common to several test cases.

Now that we’ve updated the test suite, we run it again.
Expert

Figure 5. Test results

Test results

Test results

 

Sounds good, now we can update the schema.
Expert
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    targetNamespace="http://balisage.net/todo#"
    xmlns="http://balisage.net/todo#">

    <xs:element
        name="list">
        <xs:complexType>
            <xs:sequence>
                <xs:element
                    name="title">
                    <xs:simpleType>
                        <xs:restriction
                            base="xs:token">
                            <xs:minLength
                                value="1"/>
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

todo.xsd

And run the test suite again.
Expert

Figure 6. Test results

Test results

 

Step 4: Adding todo item elements

Good. Now I want to add todo items. And lists should have at least one of them, by the way.
Customer
Sure, back to the test suite…
Expert

Test suite

(suite.xml):

<?xml version="1.0" encoding="UTF-8"?>
<tf:suite
    xmlns:tf="http://xmlschemata.org/test-first/"
    xmlns:todo="http://balisage.net/todo#"
    title="Basic tests">
    <tf:validation
        href="todo.xsd"
        type="xsd"/>
    <tf:case
        title="Empty list element"
        expected="error"
        id="root-empty">
        <todo:list/>
    </tf:case>
    <todo:list>
        <!-- Testing title elements -->
        <todo:title>
            <tf:case
                title="empty title"
                expected="error"
                id="empty-title"/>
            <tf:case
                title="non empty title"
                expected="valid"
                id="non-empty-title">A title</tf:case>
        </todo:title>
        <todo:item>
            <todo:title>A title</todo:title>
        </todo:item>
        <tf:case
            title="Un expected element"
            expected="error"
            id="unexpected">
            <todo:foo/>
        </tf:case>
    </todo:list>
    <todo:list>
        <!-- Testing todo items -->
        <todo:title>Testing todo items</todo:title>
        <tf:case
            title="No todo items"
            expected="error"
            id="no-items"/>
        <todo:item>
            <tf:case
                title="empty item"
                expected="error"
                id="empty-item"/>
            <tf:case
                title="item with a title"
                expected="valid"
                id="item-title">
                <todo:title>A title</todo:title>
            </tf:case>
        </todo:item>
    </todo:list>
    <tf:case
        title="Other root element"
        expected="error"
        id="other-root">
        <todo:title>A title</todo:title>
    </tf:case>
</tf:suite>
Let’s see what we get before any update to the schema:
Expert

Figure 7. Test results

Test results

Test results

 

It’s time to update the schema and fix what needs to be fixed:
Expert
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    targetNamespace="http://balisage.net/todo#"
    xmlns="http://balisage.net/todo#">

    <xs:element
        name="list">
        <xs:complexType>
            <xs:sequence>
                <xs:element
                    name="title">
                    <xs:simpleType>
                        <xs:restriction
                            base="xs:token">
                            <xs:minLength
                                value="1"/>
                        </xs:restriction>
                    </xs:simpleType>
                </xs:element>
                <xs:element
                    maxOccurs="unbounded"
                    name="item">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element
                                name="title">
                                <xs:simpleType>
                                    <xs:restriction
                                        base="xs:token">
                                        <xs:minLength
                                            value="1"/>
                                    </xs:restriction>
                                </xs:simpleType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

todo.xsd

And now we can check if we get it right.
Expert

Figure 8. Test results

Test results

Test results

 

Step 5: Modularizing the schema

Eric, you should be ashamed, it’s a pure Russian doll schema, not modular at all! Why not define the title and list elements globally?
Customer
Sure, we can do that! If we just change the structure of the schema, we don’t need to update the test suite and can work directly on the schema:
Expert
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    elementFormDefault="qualified"
    targetNamespace="http://balisage.net/todo#"
    xmlns="http://balisage.net/todo#">

    <xs:element
        name="list">
        <xs:complexType>
            <xs:sequence>
                <xs:element
                    ref="title"/>
                <xs:element
                    maxOccurs="unbounded"
                    ref="item"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    <xs:element
        name="title">
        <xs:simpleType>
            <xs:restriction
                base="xs:token">
                <xs:minLength
                    value="1"/>
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
    <xs:element
        name="item">
        <xs:complexType>
            <xs:sequence>
                <xs:element
                    ref="title"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

todo.xsd

But of course, each time we update the schema we must check if we’ve not introduced any bug:
Expert

Figure 9. Test results

Test results

Test results

 

Waoo, what’s happening now?
Customer
Now that our elements are global in the schema, we accept a valid title as a root element. Is that what you want?
Expert
No way, a title is not a valid list!
Customer
Then we have a number of options… We can go back to local elements and we can also add a schematron schema to check this constraint.
Expert
Schematron is fine, we’ll probably find many other constraints to check in my todo lists anyway…
Customer
OK. We still don’t have to update the test suite since we’ve not changed our requirement. Let’s write this Schematron schema then:
Expert
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://purl.oclc.org/dsdl/schematron" queryBinding="xslt2">
    <ns uri="http://balisage.net/todo#" prefix="todo"/>
    <pattern>
        <rule context="/*">
            <assert test="self::todo:list">The root element should be a todo:list</assert>
        </rule>
    </pattern>
</schema>

todo.sch

Saying that we don’t have to update the test suite wasn’t totally accurate because the schemas are referenced in ths test suite:
Expert

Test suite

(suite.xml):

<?xml version="1.0" encoding="UTF-8"?>
<tf:suite
    xmlns:tf="http://xmlschemata.org/test-first/"
    xmlns:todo="http://balisage.net/todo#"
    title="Basic tests">
    <tf:validation
        href="todo.sch"
        type="sch"/>
    <tf:validation
        href="todo.xsd"
        type="xsd"/>
    <tf:case
        title="Empty list element"
        expected="error"
        id="root-empty">
        <todo:list/>
    </tf:case>
    <todo:list>
        <todo:title>
            <tf:case
                title="empty title"
                expected="error"
                id="empty-title"/>
            <tf:case
                title="non empty title"
                expected="valid"
                id="non-empty-title">A title</tf:case>
        </todo:title>
        <todo:item>
            <todo:title>A title</todo:title>
        </todo:item>
        <tf:case
            title="Un expected element"
            expected="error"
            id="unexpected">
            <todo:foo/>
        </tf:case>
    </todo:list>
    <todo:list>
        <todo:title>Testing todo items</todo:title>
        <tf:case
            title="No todo items"
            expected="error"
            id="no-items"/>
        <todo:item>
            <tf:case
                title="empty item"
                expected="error"
                id="empty-item"/>
            <tf:case
                title="item with a title"
                expected="valid"
                id="item-title">
                <todo:title>A title</todo:title>
            </tf:case>
        </todo:item>
    </todo:list>
    <tf:case
        title="Other root element"
        expected="error"
        id="other-root">
        <todo:title>A title</todo:title>
    </tf:case>
</tf:suite>
Time to see if we’ve fixed our issue!
Expert

Figure 10. Test results

Test results

Test results

 

Great, we’ve made it, thanks!
Customer

Want to try it?

The application used to run the test suite and display its result is available at http://svn.xmlschemata.org/repository/downloads/tefisc/.

If you just want to understand how the test suite is split into XML instances, you can have a look at http://svn.xmlschemata.org/repository/downloads/tefisc/orbeon-resources/apps/tefisc/ .

In this directory:

  • split-tests.xslis the XSLT transformation that splits a test suite into top levelelement test cases. This transformation has no dependence on Orbeon Forms and can be manuallyrun against a test suite.
  • run-test.xpl is the XPL pipeline that runs a test case.
  • list-suites.xpl is the XPL pipeline that gives the list avaible test cases.
  • view.xhtml is the XForms application that displays the results.

To install this application:

  • InstallOrbeon Forms
  • copy the orbeon-resources/ directory under /WEB-INF/resources/apps/in yourorbeon webapp directory
  • or, alternatively, copy the tefisc/ directory wherever you want, edit web.xml.savto replace<param-value>/home/vdv/projects/tefisc/orbeon-resources</param-value>by the location of this directory on your filesystem, replace /WEB-INF/web.xml by this file and restart your application server.