This class models an XML node that may contain other XML nodes. XML element trees can be constructed with the class constructor and converted into XML.
Construct a new XML element and include it in an existing XMLElement tree.
# File lib/XMLElement.rb, line 23 23: def initialize(name, attributes = {}, selfClosing = false) 24: if (name.nil? && attributes.length > 0) || 25: (!name.nil? && !name.is_a?(String)) 26: raise "Name must be nil or a String " 27: end 28: @name = name 29: attributes.each do |n, v| 30: if n.nil? || v.nil? 31: raise "Attribute name (#{n}) or value (#{v}) may not be nil" 32: end 33: end 34: @attributes = attributes 35: @children = [] 36: # This can be set to true if <name /> is legal for this element. 37: @selfClosing = selfClosing 38: end
Add a new child or a set of new childs to the element.
# File lib/XMLElement.rb, line 41 41: def <<(arg) 42: # If the argument is an array, we have to insert each element 43: # individually. 44: if arg.is_a?(XMLElement) 45: @children << arg 46: elsif arg.is_a?(Array) 47: # Delete all nil entries 48: arg.delete_if { |i| i.nil? } 49: # Check that the rest are really all XMLElement objects. 50: arg.each do |i| 51: unless i.is_a?(XMLElement) 52: raise "Element must be of type XMLElement not #{i.class}" 53: end 54: end 55: @children += arg 56: elsif arg.nil? 57: # do nothing 58: else 59: raise "Elements must be of type XMLElement not #{arg.class}" 60: end 61: self 62: end
Return the value of attribute attribute.
# File lib/XMLElement.rb, line 70 70: def [](attribute) 71: @attributes[attribute] 72: end
Add or change attribute to value.
# File lib/XMLElement.rb, line 65 65: def []=(attribute, value) 66: @attributes[attribute] = value 67: end
Return the element and all sub elements as properly formatted XML.
# File lib/XMLElement.rb, line 76 76: def to_s(indent = 0) 77: out = '<' + @name 78: @attributes.keys.sort.each do |attrName| 79: out << " #{attrName}=\"#{escape(@attributes[attrName], true)}\"" 80: end 81: if @children.empty? && @selfClosing 82: out << '/>' 83: else 84: out << '>' 85: @children.each do |child| 86: # We only insert newlines for multiple childs and after a tag has been 87: # closed. 88: if @children.size > 1 && !child.is_a?(XMLText) && out[1] == >> 89: out << "\n" + indentation(indent + 1) 90: end 91: out << child.to_s(indent + 1) 92: end 93: out << "\n" + indentation(indent) if @children.size > 1 && out[1] == >> 94: out << '</' + @name + '>' 95: end 96: end
Escape special characters in input String str.
# File lib/XMLElement.rb, line 101 101: def escape(str, quotes = false) 102: out = '' 103: str.each_utf8_char do |c| 104: case c 105: when '&' 106: out << '&' 107: when '"' 108: out << '\"' 109: else 110: out << c 111: end 112: end 113: out 114: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.