-
Notifications
You must be signed in to change notification settings - Fork 0
/
XSLT for the modern web - Part 2.html
618 lines (479 loc) · 18.2 KB
/
XSLT for the modern web - Part 2.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<title>XSLT for the modern web - Part 2</title>
</head>
<body>
<main>
<section id="part-2">
<div class="container">
<h3 id="server-side">XSLT with PHP</h3>
<p>XSLT is well supported within PHP but of course you will need to install PHP first. PHP isn't available on opening the browser the way that Javascript is available without any installation. The advantage of using PHP with XSLT is that the transformation is completed server side, so will show the user the transformation regardless of what browser they are using.</p>
<p>Download PHP via the terminal:</p>
<pre><code>sudo apt-get install php</code></pre>
<p>It's useful to check your PHP version - mine has come out as 7.2</p>
<pre><code>php -v</code></pre>
<p>If you download PHP via the terminal in Linux you might find the XML modules are not downloaded. You can check whether these are installed with:</p>
<pre><code>php -i | grep "xml"</code></pre>
<p>Or you can check the modules installed:</p>
<pre><code>php -m</code></pre>
<p>If this doesn't list the below modules you won't be able to use XSLT.</p>
<pre><code>SimpleXML
...
xml
xmlreader
xmlwriter
xsl
</code></pre>
<p>To install these, try this:</p>
<pre><code>sudo apt-get install php-xml</code></pre>
<p>You can check the version of libXML like so:</p>
<pre><code>php --ri libxml
...
libxml
libXML support => active
libXML Compiled Version => 2.9.4
libXML Loaded Version => 20904
libXML streams => enabled
</code></pre>
<p>You can also check 'xml' with the above to check:</p>
<pre><code>php --ri xml
...
XML Support => active
XML Namespace Support => active
libxml2 Version => 2.9.4
</code></pre>
<p>On distros that use Yum, you can try the below:</p>
<pre><code>sudo yum -y install php-xml</code></pre>
<p>If you are using Apache2 then you will need to restart e.g.</p>
<pre><code>sudo service apache2 restart</code></pre>
<h3>Example of using DOMDocument and XSLTProcessor</h3>
<p>You might have seen references to <code>xslt_create();</code> etc these are older methods in PHP 5.6, the new method to process XSLT is <code>XSLTProcessor();</code>To use this you have to load XML and XSLT first and then use the importStyleSheet method to perform the processing.</p>
<h4>Example 7</h4>
<pre>
<code>
<?php
$xsl = "data/example.xsl";
$xml = "data/example.xml";
$xmldoc = new DOMDocument();
$xsldoc = new DOMDocument();
$xslproc = new XSLTProcessor();
if (file_exists($xml)){
if(!$xmldoc->load($xml)){
echo "could not load xml documents";
}
}
if (file_exists($xsl)){
if(!$xsldoc->load($xsl)){
echo "could not load xsl documents";
}
}
libxml_use_internal_errors(true);
$result = $xslproc->importStyleSheet($xsldoc);
if (!$result) {
foreach (libxml_get_errors() as $error) {
echo "Libxml error: {$error->message}\n";
}
}
libxml_use_internal_errors(false);
if ($result) {
echo $xslproc->transformToXML($xmldoc);
}
?>
</code>
</pre>
<h3>Example of using SimpleXML to load the XML and XSL files</h3>
<p>SimpleXML is a popular way to deal with XML files and is easier to use than DOM methods. SimpleXML provides the <code>simplexml_load_file()</code> function to load XML files. We can then use the <code>XSLTProcessor</code> to apply the transformation.</p>
<h4>Example 8</h4>
<pre>
<code>
<?php
$xsl = "data/example.xsl";
$xml = "data/example.xml";
$xmldoc = new DOMDocument();
$xsldoc = new DOMDocument();
$xslproc = new XSLTProcessor();
if (file_exists($xml)){
$xmldoc = simplexml_load_file($xml);
}
if (file_exists($xsl)){
$xsldoc = simplexml_load_file($xsl);
}
libxml_use_internal_errors(true);
$result = $xslproc->importStyleSheet($xsldoc);
if (!$result) {
foreach (libxml_get_errors() as $error) {
echo "Libxml error: {$error->message}\n";
}
}
libxml_use_internal_errors(false);
if ($result) {
echo $xslproc->transformToXML($xmldoc);
}
?>
</code>
</pre>
<h3>Using PHP and Javascript</h3>
<p>You can use PHP to do the XSLT transformation on the server and then return via AJAX/Javascript.</p>
<h4>Example 9</h4>
<p>This example uses jQuery <code>$.get</code> to call the PHP file. The PHP file then performs the XSLT transformation and the output is returned and the nodes are appended to <code><div id="example"></div></code></p>
<pre>
<code>
$.get("Example9-XSLT.php", function(data) {
$("#example").append(data);
});
</code>
</pre>
<p>This jQuery example using <code>$.ajax</code> won't work, this is because - at least in Firefox - a <code><meta></code> element is included in the output and is left open, like so <code><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></code>. As this element is not closed, <code>$.ajax</code> recognises this as inproper XML.</p><p>At some point I will revist this and see if there is a solution.</p>
<pre>
<code>
$.ajax({
type:"GET",
url: "Example9-XSLT.php",
dataType: "xml",
success: function (data) {
$("#example").append(data);
}
});
</code>
</pre>
<p>Note you can change the <code>dataType</code> to "text", but the <code><meta></code> remains.
<pre>
<code>
$.ajax({
type: "GET",
url: "Example9-XSLT.php",
dataType: "text",
success: function (data) {
$("#example").append(data);
}
});
</code>
</pre>
<p>You can also use fetch();</p>
<pre>
<code>
fetch("Example9-XSLT.php").then(function(response){
if(response){
return response.text();
}
}).then(function(data) {
$("#example").append(data);
})
.catch(function(error) {
console.log('Looks like there was a problem: ', error);
});
</code>
</pre>
<h4>Example 10</h4>
<p>Here is a more complex example of using PHP and Javascript to apply a XSLT tranformation, but also using passing a parameter to the XSLT stylesheet to present only particular books of Herodotus' Histories. Books are selected from a drop-down list.</p>
<p>Here is the HTML.</p>
<pre>
<code>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>XSLT</title>
<script type="text/javascript" src="jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Book</h2>
<form>
<select>
<option value="1">Book 1</option>
<option value="2">Book 2</option>
<option value="3">Book 3</option>
<option value="4">Book 4</option>
<option value="5">Book 5</option>
</select>
</form>
<div id="example">
</div>
<script type="text/javascript">
$(function(){
$("select").on('change', function(){
let bookVal = this.value;
$.get("Example10-XSLT.php", { book: bookVal }, function(data) {
//empty the <div> to remove any existing content
$("#example").empty();
$("#example").append(data);
});
});
});
</script>
</body>
</html>
</code>
</pre>
<p>Here is the PHP - Example10-XSLT.php. Here I am using the full Perseus text of Herodotus. I am using this line to get the value assiged to 'book' GET request <code>$book = htmlspecialchars($_GET["book"]);</code> and using this line to set the <code><xs:param></code> value book in my XSLT styesheet - <code>$xslproc->setParameter('', 'book', $book);</code>
<pre>
<code>
<?php
$xsl = "data/example-10.xsl";
$xml = "data/Perseus_text_1999.01.0126.xml";
$xmldoc = new DOMDocument();
$xsldoc = new DOMDocument();
$xslproc = new XSLTProcessor();
$book = htmlspecialchars($_GET["book"]);
if (file_exists($xml)){
$xmldoc = simplexml_load_file($xml);
}else{
echo "could not load xml document";
}
if (file_exists($xsl)){
$xsldoc = simplexml_load_file($xsl);
}else{
echo "could not load xsl document";
}
libxml_use_internal_errors(true);
$xslproc->setParameter('', 'book', $book);
$result = $xslproc->importStyleSheet($xsldoc);
if (!$result){
foreach (libxml_get_errors() as $error){
echo "Libxml error: {$error->message}\n";
}
}
libxml_use_internal_errors(false);
if ($result){
echo $xslproc->transformToXML($xmldoc);
}
?>
</code>
</pre>
<p>Here is the XSLT stylesheet which has been adapted to progress templates on the basis of Book number. There are otherways of achieving the same result, this is just an example.</p>
<pre>
<code>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:param name="book" select="1"/>
<xsl:template match="/">
<xsl:apply-templates/>
</xsl:template>
<xsl:template match="div1[@type='Book']">
<xsl:if test="@n = $book">
<h2>Book <xsl:value-of select="$book"/></h2>
<xsl:apply-templates/>
</xsl:if>
</xsl:template>
<xsl:template match="teiHeader"/>
</xsl:stylesheet>
</code>
</pre>
<h3>HTML5 DOCTYPE</h3>
<p>to note: exporting HTML5 doctype as <code><xsl:text disable-output-escaping='yes'><!DOCTYPE html></xsl:text></code>. If you inspect in Mozilla Firefox it seems the <code><?xml version="1.0"?></code> is also exported. (verify) This is an optional feature which processors are not required to implement, and in XSLT 2.0 it is deprecated.</p>
<p>This could be an alternative:</p>
<code><xsl:output method="html" doctype-system="about:legacy-compat"/></code>
<p>I read this here: http://www.microhowto.info/howto/generate_an_html5_doctype_using_xslt.html</p>
<p>You can also combine using AJAX, PHP and XSLT to do some interesting things. Whether you might want to in a production environment is another question...there are always other ways to achieve what you need.</p>
<p>Here's an example idea to show information based on a drop-down. AJAX returns a parameter to a PHP script which in turn uses XSLT to pick out information from a XML document.</p>
<h3>XPath in Javascript</h3>
<p>XPath is a path-based syntax used to select features of XML documents. It can select individual or groups of elements (node sets), text content and attribute content. It can also be used to count number of elements or attributes.</p>
<p>The official specification can be found here: </p>
<p>You should check the level of XPath that is available to you in different contexts, when it doubt assume 1.0 is available.</p>
<p>XPath can be used in Javascript through <code>document.evaluate</code>. This can be used on the HTML document itself or on a loaded XML document. We can load the XML file using the javascript already reviewed.</p>
<p>In this case I am using the JQuery <code>get()</code> method we have used previously to load the XML document, then using <code>evaluate</code> to apply a XPath expression to the XML document. The convention appears to be that a try-catch block is used with a iterator method <code>iterateNext</code>.
<pre>
<code>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>XPath</title>
<script type="text/javascript" src="jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Herodotus</h2>
<div id="example">
</div>
<script type="text/javascript">
(function(){
if (!('XPathEvaluator' in window)) {
console.log('XPath does not appear to be available in this browser. Please try another.');
return;
}else{
console.log('XPath available.');
}
$.get("data/Perseus_text_1999.01.0126.xml", function(doc) {
let xpath = doc.evaluate('//div1[@type="Book" and @n=1]//milestone[@unit="chapter" and @n="1"]', doc, null, XPathResult.ANY_TYPE, null);
let output = [];
let count = 0;
try {
let node = xpath.iterateNext();
while (node) {
count++;
output.push("<h3>Chapter" + count + "<h3>" + node.textContent + "<br/>");
node = xpath.iterateNext();
}
}
catch (e) {
alert( 'Error: Document tree modified during iteration ' + e );
}
$("#example").append(names.join(" "));
});
})();
</script>
</body>
</html>
</code>
</pre>
<h4>Useful XPath</h4>
<p>There are many resources on XPath, in essence these are the most useful patterns to know. As the Perseus' Digital Library Herodotus document is a TEI document these examples you might encounter when trying to use XPath to navigate around a TEI document. </p>
<table>
<tr>
<td>.</td>
<td>The context node - this can be used to assign an XPath relative to the current location. </td>
</tr>
<tr>
<td>/</td>
<td>The root node - can be the starting point if XPath is required to match from the root node</td>
</tr>
<tr>
<td>//</td>
<td>- matches self or descendents - this is often used if you want to match all elements with a particular name e.g. this XPath count(//name) returns counts all name elements in the document.</td>
</tr>
<tr>
<td>section/*/note</td>
<td>Matches notes that are descendants of section, with an unspecified element between section and note. I.e this selects notes that are grandchildren of section.</td>
</tr>
<tr>
<td>//category/catDesc</td>
<td>If you know the document and know you want the first item you can use this format. Here the match is made on all catDesc elements that are childen of category elements. </td>
</tr>
<tr>
<td>//category/catDesc[.="Drama"]</td>
<td>Here is an example using the current node to match those catDesc elements which have the text content "Drama" and who are children of a category element</td>
</tr>
<tr>
<td>//category[catDesc="Drama"]</td>
<td>Here is an example using the current node to match those category elements which have a catDesc child with the text content "Drama". Compare this with the above example - this path matches category element, whereas the above example matches the catDesc elements.</td>
</tr>
<tr>
<td>//milestone[@unit]</td>
<td>Matches milestone that have a unit attribute.</td>
</tr>
<tr>
<td>//milestone[@unit="chapter"]</td>
<td>Matches milestone that have a unit attribute equal to "chapter" - i.e match all chapters.</td>
</tr>
<tr>
<td>div1 | milestone</td>
<td>Matches div1 or milestone elements</td>
</tr>
<tr>
<td>count(//milestone[@unit="chapter"])</td>
<td>counts the number of milestone elements that have a unit attribute with the value "chapter" i.e counts all the chapters.</td>
</tr>
<tr>
<td>//div1[@type="Book" and @n=1]//name[@type="pers"]</td>
<td>Matches name elements with attribute type of "pers" that are descendents of div1 element with type attribute of "Book" and n attribute of "1" (i.e Book 1) - i.e match all named persons in Book 1.</td>
</tr>
<tr>
<td>//div1[@type="Book" and @n=1]//milestone[@unit="chapter" and @n="1"]</td>
<td>Matches milestone elements with attribute unit of "chapter" and arribute n of "1" that are descendents of div1 element with type attribute of "Book" and n attribute of "1" (i.e Book 1) - i.e match chapter 1 within book 1</td>
</tr>
<tr>
<td>//div1[@type="Book" and @n=1]//milestone[@unit="chapter"][position() = last()]</td>
<td>Matches the last chapter from book 1.</td>
</tr>
<tr>
<td>element[not(@id)]</td>
<td>Matches elements that don't have an id attribute</td>
</tr>
</table>
</br>
<h4>XPath in PHP</h4>
<p>To use use XPath in PHP, use either the <code>query()</code> or <code>evaluate()</code> methods of <a href="https://www.php.net/manual/en/class.domxpath.php" title="PHP.net | DOMXPATH">DOMXPath</a>, a class of the PHP XML DOM or use <a href="https://www.php.net/manual/en/simplexmlelement.xpath" title="PHP.net | PHP:SimpleXMLElement::xpath">SimpleXMLElement::xpath</a> which is a SimpleXML method to match XPath expressions.</p>
<h3>DOMXPath</h3>
<p>DOMXPath supports XPath 1.0</p>
<h4>Example 12</h4>
<p>This example uses the DOMXPath <code>query()</code> method which should be used when a DOM NodeList is the expected return type when the XPath expression is applied. Note the various <code>libxml</code> functions which will help pick up errors in the XPath expression. </p>
<pre>
<code>
<?php
$xml = "data/Perseus_text_1999.01.0126.xml";
$xmldoc = new DOMDocument();
if (file_exists($xml)){
if(!$xmldoc->load($xml)){
echo "could not load xml documents";
}
libxml_use_internal_errors(true);
$xpath = new DOMXPath($xmldoc);
$nodes = $xpath->query('//milestone[@unit="chapter"]');
if(!$nodes){
foreach (libxml_get_errors() as $error) {
echo "Libxml error: {$error->message}\n";
}
}else{
foreach($nodes as $node){
echo $node->tagName;
}
}
libxml_use_internal_errors(false);
}
?>
</code>
</pre>
<h4>Example 13</h4>
<p>This example uses the DOMXPath <code>evaluate()</code> method which should be used when a typed return from the XPath is expected to be returned - i.e a number or text string is expected rather than a DOM NodeList.</p>
<pre>
<code>
<?php
$xml = "data/Perseus_text_1999.01.0126.xml";
$xmldoc = new DOMDocument();
if (file_exists($xml)){
if(!$xmldoc->load($xml)){
echo "could not load xml documents";
}
libxml_use_internal_errors(true);
$xpath = new DOMXPath($xmldoc);
$count = $xpath->evaluate('count(//milestone[@unit="chapter"])');
if(!$count){
foreach (libxml_get_errors() as $error) {
echo "Libxml error: {$error->message}\n";
}
}else{
echo "There are {$count} chapters";
}
libxml_use_internal_errors(false);
}
?>
</code>
</pre>
<h3>SimpleXML</h3>
<p>SimpleXML provides another way to traverse XML documents. It includes a simple way to apply XPath expressions.</p>
<h4>Example 14</h4>
<pre>
<code>
<?php
$xml = "data/Perseus_text_1999.01.0126.xml";
if (file_exists($xml)){
$xmldoc = simplexml_load_file($xml);
libxml_use_internal_errors(true);
$result = $xmldoc->xpath('//milestone[@unit="chapter"]');
if(!$result){
foreach (libxml_get_errors() as $error) {
echo "Libxml error: {$error->message}\n";
}
}else{
foreach ($result as $node) {
echo "This book includes {$node[unit]} {$node[n]}";
}
}
libxml_use_internal_errors(false);
}else{
echo 'could not load XML document';
}
?>
</code>
</pre>
</div>
</section>
</main>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
</body>
</html>