Skip to content

Instantly share code, notes, and snippets.

@yuuki
Created June 11, 2011 17:30
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 yuuki/1020779 to your computer and use it in GitHub Desktop.
Save yuuki/1020779 to your computer and use it in GitHub Desktop.
print arranged Xml
#! /usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'optparse'
Version = "0.1.0"
$arg_options = Hash.new
$arg_options[:t] = false
$opts = OptionParser.new {|opt|
begin
opt.banner = "usage: #{opt.program_name} xmlfile"
opt.on('-t', '--text', 'text-only extract mode') {|v| $arg_options[:t] = true}
opt.parse!(ARGV)
rescue OptionParser::ParseError => e
$stderr.print e
$stderr.puts opt.banner
exit
end
}
class XmlPrinterException < Exception; end
class XmlPrinter
def initialize(data)
@xml_data = data
@result = ""
end
def print()
depth = 0
@xml_data.scan(/<.*?>|<\/.*?>|<.*?\/>|.*?(?=<)/).each do |line|
line.strip!
if normaltag?(line) then
if starttag?(line) then
add_string(line, depth)
depth += 1
elsif endtag?(line) then
depth -= 1
add_string(line, depth)
elsif emptytag?(line) then
add_string(line, depth)
else
$stderr.puts line
raise XmlPrinterException.new, 'xml format error'
end
else # tag includeing text
depth += 1
add_string(line, depth)
depth -= 1
if $arg_options[:t] then
@result += line
end
end
end
return @result
end
private
def add_string(line, depth)
if $arg_options[:t] == false then
@result += " " * depth + line + "\n"
end
end
def normaltag?(line)
return (line[0] == '<' && line[-1] == '>')
end
def starttag?(line)
return (line[1] != '/' && line[-2] != '/')
end
def endtag?(line)
return (line[1] == '/' && line[-2] != '/')
end
def emptytag?(line)
return (line[1] != '/' && line[-2] == '/')
end
end
def print_xmlfile(xmlfile)
if File.file?(xmlfile) == false then
if File.directory?(xmlfile) then
$stderr.print "#{xmlfile} is directory"
else
$stderr.print "#{xmlfile} : no such file or directory"
end
$stderr.print $opts.help
exit
end
xml_data = ""
File.open(xmlfile) {|f|
xml_data = f.read
}
begin
printer = XmlPrinter.new(xml_data)
printed_data = printer.print
print printed_data
rescue XmlPrinterException => e
p e
exit
end
end
def main()
if ARGV.size == 0 then
$stderr.print "too few arguments"
$stderr.print $opts.help
exit
end
ARGV.each do |arg|
print_xmlfile(arg)
end
exit
end
if __FILE__ == $0 then
main()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment