Created
October 11, 2012 20:11
-
-
Save sstelfox/3875186 to your computer and use it in GitHub Desktop.
Quick Way to make Minified HTML readable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
SOURCE_PAGE="http://google.com/" | |
DEST_FILE="formatted-google-homepage.html" | |
require "nokogiri" | |
require "open-uri" | |
pretty_print_xsl = <<-EOS | |
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> | |
<xsl:output method="xml" encoding="ISO-8859-1"/> | |
<xsl:param name="indent-increment" select="' '"/> | |
<xsl:template name="newline"> | |
<xsl:text disable-output-escaping="yes"> | |
</xsl:text> | |
</xsl:template> | |
<xsl:template match="comment() | processing-instruction()"> | |
<xsl:param name="indent" select="''"/> | |
<xsl:call-template name="newline"/> | |
<xsl:value-of select="$indent"/> | |
<xsl:copy /> | |
</xsl:template> | |
<xsl:template match="text()"> | |
<xsl:param name="indent" select="''"/> | |
<xsl:call-template name="newline"/> | |
<xsl:value-of select="$indent"/> | |
<xsl:value-of select="normalize-space(.)"/> | |
</xsl:template> | |
<xsl:template match="text()[normalize-space(.)='']"/> | |
<xsl:template match="*"> | |
<xsl:param name="indent" select="''"/> | |
<xsl:call-template name="newline"/> | |
<xsl:value-of select="$indent"/> | |
<xsl:choose> | |
<xsl:when test="count(child::*) > 0"> | |
<xsl:copy> | |
<xsl:copy-of select="@*"/> | |
<xsl:apply-templates select="*|text()"> | |
<xsl:with-param name="indent" select="concat ($indent, $indent-increment)"/> | |
</xsl:apply-templates> | |
<xsl:call-template name="newline"/> | |
<xsl:value-of select="$indent"/> | |
</xsl:copy> | |
</xsl:when> | |
<xsl:otherwise> | |
<xsl:copy-of select="."/> | |
</xsl:otherwise> | |
</xsl:choose> | |
</xsl:template> | |
</xsl:stylesheet> | |
EOS | |
source_html = open(SOURCE_PAGE) { |f| f.read } | |
xsl = Nokogiri::XSLT(pretty_print_xsl) | |
html = Nokogiri(source_html) | |
File.open(DEST_FILE, 'w') { |f| f << xsl.apply_to(html).to_s } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment