File: libxml.rb

package info (click to toggle)
libxml-ruby 0.5.2.0-3%2Blenny1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 652 kB
  • ctags: 875
  • sloc: ansic: 5,874; ruby: 1,524; xml: 144; makefile: 9
file content (99 lines) | stat: -rw-r--r-- 1,645 bytes parent folder | download
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# $Id: libxml.rb 134 2007-08-29 17:30:19Z danj $ 
# Please see the LICENSE file for copyright and distribution information 
require 'xml/libxml_so'

class XML::Document
  include Enumerable

  # maybe, maybe not...
  def each(&blk)
    find('//*').each(&blk)
  end
end

class XML::Node::Set 
  include Enumerable 

  # inefficient, but maybe can find a way to cache the
  # ary and dump on change?
  def [](i, count = nil) 
    if count
      to_a[i,count]
    else
      to_a[i]
    end
  end

  def to_s #:nodoc:
    to_a.to_s
  end
end

module XML::SiblingEnum
  private 
  
  # Iterates nodes and attributes
  def siblings(node, &blk)
    if n = node
      loop do
        blk.call(n)
        break unless n = n.next
      end
    end 
  end
end

class XML::Node
  include XML::SiblingEnum
  include Enumerable
  include Comparable
  
  # maybe these don't belong on all nodes...
  def each_child(&blk)
    siblings(child, &blk)   
  end

  def each_attr(&blk)
    siblings(properties, &blk)
  end

  # all siblings INCLUDING self
  def each_sibling(&blk)
    siblings(self, &blk)
  end
  
  # I guess this is what you'd expect?
  alias :each :each_child

  def to_a
    inject([]) { |ary,n| ary << n }
  end
  
  def <=>(other)
    to_s <=> other.to_s
  end  
end

class XML::Attr 
  include XML::SiblingEnum
  include Enumerable

  def each_sibling(&blk)
    siblings(self,&blk)
  end
  
  alias :each_attr :each_sibling
  alias :each :each_sibling
  
  def to_h
    inject({}) do |h,a| h[a.name] = a.value end
  end

  def to_a
    inject([]) do |ary,a| ary << [a.name, a.value] end
  end
  
  def to_s
    "#{name} = #{value}"
  end
end