Class: LibXmlNode

Inherits:
Object
  • Object
show all
Defined in:
lib/libxml_to_hash.rb

Overview

This class is required to represent Nodes that contain attributes as well as other content, for example: <karin zak=“lebt”>schon</karin> We cannot non-ambigiously represent this node as a hash because Hashes may contain arbitrary keys. Having a separate class for representing such nodes allows for easy testing for the class (which we have to do anyway since hash values may be Strings, Arrays or other Hashes already) Update: No need for testing when using the iterable method. Usage: LibXmlNode.new(“karin”, “zak”)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLibXmlNode

Returns a new instance of LibXmlNode.



25
26
27
28
29
# File 'lib/libxml_to_hash.rb', line 25

def initialize
  @subnodes = {}
  @attributes = {}
  @text = ""
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



22
23
24
# File 'lib/libxml_to_hash.rb', line 22

def attributes
  @attributes
end

#subnodesObject

Returns the value of attribute subnodes.



21
22
23
# File 'lib/libxml_to_hash.rb', line 21

def subnodes
  @subnodes
end

#textObject

Returns the value of attribute text.



23
24
25
# File 'lib/libxml_to_hash.rb', line 23

def text
  @text
end

Class Method Details

.create(n, a, t) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/libxml_to_hash.rb', line 31

def self.create(n, a, t)
  l = LibXmlNode.new
  l.subnodes = n
  l.attributes = a
  l.text = t
  l
end

Instance Method Details

#==(other) ⇒ Object



71
72
73
74
75
76
77
78
# File 'lib/libxml_to_hash.rb', line 71

def ==(other)
  if other.class == LibXmlNode
    if @subnodes == other.subnodes and @attributes == other.attributes and @text == other.text
      return true
    end
  end
  false
end

#add_attribute(key, value) ⇒ Object



39
40
41
# File 'lib/libxml_to_hash.rb', line 39

def add_attribute(key, value)
  @attributes[key] = value
end

#add_node(key, value) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/libxml_to_hash.rb', line 43

def add_node(key, value)
  if @subnodes[key] 
    if @subnodes[key].is_a? Object::Array
      @subnodes[key] << value
    else
      @subnodes[key] = [@subnodes[key], value]
    end
  else
    @subnodes[key] = value
  end
end

#add_text(t) ⇒ Object



55
56
57
# File 'lib/libxml_to_hash.rb', line 55

def add_text(t)
  @text << t
end

#iterableObject



80
81
82
# File 'lib/libxml_to_hash.rb', line 80

def iterable
  [self]
end

#simplifyObject



59
60
61
62
63
64
65
66
67
68
69
# File 'lib/libxml_to_hash.rb', line 59

def simplify
  if @attributes.empty?
    if @text == ""
      return @subnodes
    end
    if @subnodes == {}
      return @text
    end
  end
  return self
end