Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created May 14, 2020 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/5b35874527c49468f5e6f1fe6c31b49e to your computer and use it in GitHub Desktop.
Save tomhodgins/5b35874527c49468f5e6f1fe6c31b49e to your computer and use it in GitHub Desktop.
<ul>
<li>
<a href="https://example.com/page1" title="Last updated 2020-05-08T09:35:39+01:00">https://example.com/page1</a>
</li>
<li>
<a href="https://example.com/page2" title="Last updated 2020-05-08T09:35:39+01:00">https://example.com/page2</a>
</li>
<li>
<a href="https://example.com/page3" title="Last updated 2020-05-13T13:49:48+01:00">https://example.com/page3</a>
</li>
</ul>
function xslt(html = '', xsl = '') {
const processor = new XSLTProcessor
processor.importStylesheet(
new DOMParser().parseFromString(xsl, 'application/xml')
)
return processor.transformToFragment(
new DOMParser().parseFromString(html, 'text/html'),
document
)
}
const data = `
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://example.com/page1</loc>
<lastmod>2020-05-08T09:35:39+01:00</lastmod>
</url>
<url>
<loc>https://example.com/page2</loc>
<lastmod>2020-05-08T09:35:39+01:00</lastmod>
</url>
<url>
<loc>https://example.com/page3</loc>
<lastmod>2020-05-13T13:49:48+01:00</lastmod>
</url>
</urlset>
`
const stylesheet = `
<xsl:stylesheet
xmlns="http://www.w3.org/1999/xhtml"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9"
>
<xsl:output
method="html"
encoding="utf-8"
indent="yes"
media-type="text/html"
omit-xml-declaration="yes"
doctype-system="about:legacy-compat"
/>
<xsl:template match="//node()[local-name() = name()]">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="/">
<html>
<xsl:apply-templates />
</html>
</xsl:template>
<xsl:template match="//sitemap:urlset">
<ul>
<xsl:for-each select="sitemap:url">
<li><a href="{sitemap:loc}" title="Last updated {sitemap:lastmod}"><xsl:value-of select="sitemap:loc" /></a></li>
</xsl:for-each>
</ul>
</xsl:template>
</xsl:stylesheet>
`
// Transform data with XSL stylesheet
console.log(
xslt(data, stylesheet)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment