MENU
XPath & XSLT
XPath is a language for selecting nodes from an XML document. It can also be used to compute values in the context of an XML document.
RESETRUNFULL
<!DOCTYPE html><html lang="en"><body>
<div>
<p id="p1">300</p>
<p id="p2">400</p>
</div>
<script>
var data =
`<?xml version="1.0"?>
<menu restaurant="Golden Outlet">
<dish id="1">Satay <i>Cooked</i></dish>
<drink id="2">Cola</drink>
<dish id="3">Curry Chicken</dish>
<dish id="4" xmlns="http://example.com">
Sweet and Sour Pork
</dish>
</menu>`;
let xml = (new DOMParser).parseFromString(data, 'text/xml')
let evaluator = new XPathEvaluator();
const b = "<br/>";
// evaluating from XML document
document.write(xml.evaluate("//drink/text() = 'Cola'", xml, null, XPathResult.BOOLEAN_TYPE, null).booleanValue + b); // true
// evaluating from XPath evaluator
document.write(evaluator.evaluate("/menu/dish", xml, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE).snapshotLength + b); // 2
// evaluating from XPath expression
let expression = evaluator.createExpression("//dish[@id=3]/text()");
document.write(expression.evaluate(xml, XPathResult.STRING_TYPE).stringValue + b); // Curry Chicken
// evaluating from HTML document
document.write(document.evaluate("count(//p)", document, null, XPathResult.ANY_TYPE,null).numberValue + b); // 2
</script>
</body></html>
Extensible Stylesheet Language Transformations (XSLT) is a language for transforming XML documents.
Below, we try to transform XML into HTML.
RESETRUNFULL
RESETRUNFULL
<?xml version="1.0" encoding="UTF-8" ?><!-- people.xml -->
<people>
<person>
<name>Eric Lee</name>
<gender>m</gender>
<age>35</age>
</person>
<person>
<name>Serena</name>
<gender>f</gender>
<age>25</age>
</person>
</people>
<?xml version="1.0" encoding="UTF-8"?><!-- people.xslt -->
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" version="5.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="people">
<table border="1">
<xsl:for-each select="person">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="gender"/></td>
<td><xsl:value-of select="age"/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
<!DOCTYPE html><html><head></head><body></body>
<script>
function loadXMLDoc(file){
xhr=new XMLHttpRequest();
xhr.open("GET",file,false);
xhr.responseType ='msxml-document';
xhr.send();
return xhr.responseXML;
}
XML = loadXMLDoc("/shared/people.xml");
XSLT = loadXMLDoc("/shared/people.xslt");
if (document.implementation && document.implementation.createDocument){
xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(XSLT);
newXML = xsltProcessor.transformToFragment(XML, document);
document.querySelector("body").appendChild(newXML);
}
</script></html>
Detailed explanations of how XPath and XSLT work are beyond the scope of this book.