# ----------------------------------------------------------------------------------------------- # Author: Dean Stringer # Description: # takes an XML filename as input, parses each line escaping all bracket # characters and wrapping tags and attributes in tahs so the XML # can be displayed in a webpage # # can output CSS styles to render a page in Mozilla/Firefox colours # or the Microsoft/IE engine colours # # Notes: # (1) this script would be more reliably implemented as an XSLT # transform, or at least using an XML parser then DOM methods # to step through and output the results, but hey, its simple, # has no dependencies, and works in many cases just fine. # # (2) watch file bloat, the output will be considerable bigger than # the input XML file # # (3) have tested the output in Mozilla, Firefox, IE6, Netscape4.7 # Opera7.54 and seemed to render OK # ----------------------------------------------------------------------------------------------- unless (@ARGV > 0) { die "XMLPretty: converts XML to a colorised browser friendly HTML\nSyntax: $0 "; } # set Mozilla-like XML rendering colours/styles. my $style = 'Mozilla'; my $styleTag = 'color: #990099; font-weight: bold;'; my $styleAttrib = 'color: #000000; font-weight: bold;'; my $styleAttribVal = 'color: #0000ff;'; my $styleBracket = 'color: #0000CC;'; my $styleBody = 'color: #000000; font-size: 0.95em;'; my $styleComment = 'color: #006600; font-style: italic;'; my $stylePI = 'color: #990099; '; # override if you want the Microsoft/IE XML rendering colours if ($style ne 'Mozilla') { $styleTag = 'color: #660000;'; $styleAttrib = 'color: #ee0000;'; $styleBracket = 'color: #0000CC;'; $styleAttribVal = 'color: #000000;'; $styleBody = 'color: #000000; font-family: courier, sans-serif; font-size: 0.9em;'; $styleComment = 'color: #666666; '; $stylePI = 'color: #006633; '; } my $tabSize = 2; my $fileName = shift; open INFILE, "< $fileName"; print "
"; while (my $line = ) { # replace left and right hand '>'s $line =~ s/>/>/g; $line =~ s/" . $line . ''; next; # dont bother with the other checks for PI's } # check if a comment if ($line =~ /\s*<!--(.+)-->\s*/) { print "
<!-- $1 -->"; next; # dont bother with the other checks for comments } # attriubute names, look for name=" or name=' or name = ' etc $line =~ s/([a-z0-9_:\-]+)\s*=\s*('|"){1}/$1<\/span>=$2/ig; # attriubute values $line =~ s/='([\w\/\[\]\@="]+)'/='<\/span>$1<\/span>'<\/span>/ig; $line =~ s/="([\w\/\[\]\@=']+)"/="<\/span>$1<\/span>"<\/span>/ig; # opening tags, look for '<' followed by a tagname $line =~ s/<([a-z0-9_:\-]+)/<$1<\/span>/ig; # closing tags, look for '<' followed by a tagname $line =~ s/([a-z0-9_:\-]+)>/$1<\/span>>/ig; $line =~ s/("|')\s+/$1/g; # remove space after quotes $line =~ s/(\s){$tabSize}/  /g; # pad/indent stuff $line =~ s/^\s+/ /g; # remove any leading whitespace # IE colours brackets, so them as well $line =~ s/</<<\/span>/g; $line =~ s/>/><\/span>/g; print "
" . $line; } print "
"; close INFILE