1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#!/usr/bin/env ruby -w
# encoding: UTF-8
#
# = XMLDocument.rb -- The TaskJuggler III Project Management Software
#
# Copyright (c) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014
# by Chris Schlaeger <cs@taskjuggler.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
require 'taskjuggler/XMLElement'
class TaskJuggler
# This class provides a rather simple XML document generator. It provides
# basic features to create a tree of XMLElements and to generate a XML String
# or file. It's much less powerful than REXML but provides a more efficient
# API to create XMLDocuments with lots of attributes.
class XMLDocument
# Create an empty XML document.
def initialize(&block)
@elements = block ? yield(block) : []
end
# Add a top-level XMLElement.
def <<(arg)
if arg.is_a?(Array)
@elements += arg.flatten
elsif arg.nil?
# do nothing
elsif arg.is_a?(XMLElement)
@elements << arg
else
raise ArgumentError, "Unsupported argument of type #{arg.class}: " +
"#{arg.inspect}"
end
end
# Produce the XMLDocument as String.
def to_s
str = ''
@elements.each do |element|
str << element.to_s(0)
end
str
end
# Write the XMLDocument to the specified file.
def write(filename)
f = filename == '.' ? $stdout : File.new(filename, 'w')
@elements.each do |element|
f.puts element.to_s(0)
end
f.close unless f == $stdout
end
end
end
|