Class: Oga::XML::Element

Inherits:
Node
  • Object
show all
Includes:
Querying
Defined in:
lib/oga/xml/element.rb

Overview

Class that contains information about an XML element such as the name, attributes and child nodes.

Constant Summary collapse

XMLNS_PREFIX =

The attribute prefix/namespace used for registering element namespaces.

Returns:

  • (String)
'xmlns'.freeze

Instance Attribute Summary collapse

Attributes inherited from Node

#node_set

Instance Method Summary collapse

Methods included from Querying

#at_css, #at_xpath, #css, #xpath

Methods inherited from Node

#after, #before, #children, #children=, #html?, #next, #next_element, #parent, #previous, #previous_element, #remove, #replace, #root_node, #xml?

Methods included from Traversal

#each_node

Constructor Details

#initialize(options = {}) ⇒ Element

Returns a new instance of Element.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :name (String)

    The name of the element.

  • :namespace_name (String)

    The name of the namespace.

  • :attributes (Array<Oga::XML::Attribute>)

    The attributes of the element as an Array.



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/oga/xml/element.rb', line 39

def initialize(options = {})
  super

  @name           = options[:name]
  @namespace_name = options[:namespace_name]
  @attributes     = options[:attributes] || []
  @namespaces     = options[:namespaces] || {}

  link_attributes
  register_namespaces_from_attributes
end

Instance Attribute Details

#attributesArray<Oga::XML::Attribute>

Returns:



17
18
19
# File 'lib/oga/xml/element.rb', line 17

def attributes
  @attributes
end

#nameString

Returns:

  • (String)


14
15
16
# File 'lib/oga/xml/element.rb', line 14

def name
  @name
end

#namespace_nameString

Returns:

  • (String)


11
12
13
# File 'lib/oga/xml/element.rb', line 11

def namespace_name
  @namespace_name
end

#namespacesHash

Returns the namespaces registered on this element, or an empty Hash in case of an HTML element.

Returns:

  • (Hash)


177
178
179
# File 'lib/oga/xml/element.rb', line 177

def namespaces
  html? ? {} : @namespaces
end

Instance Method Details

#add_attribute(attribute) ⇒ Object

Adds a new attribute to the element.

Parameters:



106
107
108
109
110
# File 'lib/oga/xml/element.rb', line 106

def add_attribute(attribute)
  attribute.element = self

  attributes << attribute
end

#attribute(name) ⇒ Oga::XML::Attribute Also known as: attr

Returns an attribute matching the given name (with or without the namespace).

Examples:

# find an attribute that only has the name "foo"
attribute('foo')

# find an attribute with namespace "foo" and name bar"
attribute('foo:bar')

Parameters:

  • name (String|Symbol)

    The name (with or without the namespace) of the attribute.

Returns:



75
76
77
78
79
80
81
82
83
# File 'lib/oga/xml/element.rb', line 75

def attribute(name)
  name, ns = split_name(name)

  attributes.each do |attr|
    return attr if attribute_matches?(attr, ns, name)
  end

  return
end

#available_namespacesHash

Returns a Hash containing all the namespaces available to the current element.

Returns:

  • (Hash)


311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/oga/xml/element.rb', line 311

def available_namespaces
  # HTML(5) completely ignores namespaces
  unless @available_namespaces
    if html?
      @available_namespaces = {}
    else
      merged = namespaces.dup
      node   = parent

      while node && node.respond_to?(:namespaces)
        node.namespaces.each do |prefix, ns|
          merged[prefix] = ns unless merged[prefix]
        end

        node = node.parent
      end

      @available_namespaces = merged
    end
  end

  @available_namespaces
end

#default_namespace?TrueClass|FalseClass

Returns true if the current element resides in the default XML namespace.

Returns:

  • (TrueClass|FalseClass)


187
188
189
# File 'lib/oga/xml/element.rb', line 187

def default_namespace?
  namespace == DEFAULT_NAMESPACE || namespace.nil?
end

#flush_namespaces_cacheObject

Flushes the namespaces cache of the current element and all its child elements.



356
357
358
359
360
361
362
363
# File 'lib/oga/xml/element.rb', line 356

def flush_namespaces_cache
  @available_namespaces = nil
  @namespace            = nil

  children.each do |child|
    child.flush_namespaces_cache if child.is_a?(Element)
  end
end

#get(name) ⇒ Object

Returns the value of the given attribute.

Examples:

element.get('class') # => "container"

See Also:

  • Oga::XML::Element.[[#attribute]


95
96
97
98
99
# File 'lib/oga/xml/element.rb', line 95

def get(name)
  found = attribute(name)

  found ? found.value : nil
end

#inner_textString

Returns the text of the current element only.

Returns:

  • (String)


205
206
207
208
209
210
211
212
213
# File 'lib/oga/xml/element.rb', line 205

def inner_text
  text = ''

  text_nodes.each do |node|
    text << node.text
  end

  text
end

#inner_text=(text) ⇒ Object

Sets the inner text of the current element to the given String.

Parameters:

  • text (String)


236
237
238
239
# File 'lib/oga/xml/element.rb', line 236

def inner_text=(text)
  text_node = XML::Text.new(:text => text)
  @children = NodeSet.new([text_node], self)
end

#inspectString

Returns:

  • (String)


270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/oga/xml/element.rb', line 270

def inspect
  segments = []

  [:name, :namespace, :attributes, :children].each do |attr|
    value = send(attr)

    if !value or (value.respond_to?(:empty?) and value.empty?)
      next
    end

    segments << "#{attr}: #{value.inspect}"
  end

  "Element(#{segments.join(' ')})"
end

#namespaceOga::XML::Namespace

Returns the namespace of the element.

Returns:



162
163
164
165
166
167
168
169
# File 'lib/oga/xml/element.rb', line 162

def namespace
  unless @namespace
    available  = available_namespaces
    @namespace = available[namespace_name] || available[XMLNS_PREFIX]
  end

  @namespace
end

#register_namespace(name, uri, flush = true) ⇒ Object

Registers a new namespace for the current element and its child elements.

Parameters:

  • name (String)
  • uri (String)
  • flush (TrueClass|FalseClass) (defaults to: true)

See Also:

  • Oga::XML::Element.[Oga[Oga::XML[Oga::XML::Namespace[Oga::XML::Namespace#initialize]


295
296
297
298
299
300
301
302
303
# File 'lib/oga/xml/element.rb', line 295

def register_namespace(name, uri, flush = true)
  if namespaces[name]
    raise ArgumentError, "The namespace #{name.inspect} already exists"
  end

  namespaces[name] = Namespace.new(:name => name, :uri => uri)

  flush_namespaces_cache if flush
end

#self_closing?TrueClass|FalseClass

Returns true if the element is a self-closing element.

Returns:

  • (TrueClass|FalseClass)


340
341
342
343
344
345
346
347
348
349
350
# File 'lib/oga/xml/element.rb', line 340

def self_closing?
  self_closing = children.empty?
  root         = root_node

  if root.is_a?(Document) and root.html? \
  and !HTML_VOID_ELEMENTS.allow?(name)
    self_closing = false
  end

  self_closing
end

#set(name, value) ⇒ Object

Sets the value of an attribute to the given value. If the attribute does not exist it is created automatically.

Parameters:

  • name (String)

    The name of the attribute, optionally including the namespace.

  • value (String)

    The new value of the attribute.



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/oga/xml/element.rb', line 121

def set(name, value)
  found = attribute(name)

  if found
    found.value = value
  else
    if name.include?(':')
      ns, name = name.split(':')
    else
      ns = nil
    end

    attr = Attribute.new(
      :name           => name,
      :namespace_name => ns,
      :value          => value
    )

    add_attribute(attr)
  end
end

#textString

Returns the text of all child nodes joined together.

Returns:

  • (String)


196
197
198
# File 'lib/oga/xml/element.rb', line 196

def text
  children.text
end

#text_nodesOga::XML::NodeSet

Returns any Text nodes that are a direct child of this element.

Returns:



221
222
223
224
225
226
227
228
229
# File 'lib/oga/xml/element.rb', line 221

def text_nodes
  nodes = NodeSet.new

  children.each do |child|
    nodes << child if child.is_a?(Text)
  end

  nodes
end

#to_xmlString

Converts the element and its child elements to XML.

Returns:

  • (String)


246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/oga/xml/element.rb', line 246

def to_xml
  if namespace_name
    full_name = "#{namespace_name}:#{name}"
  else
    full_name = name
  end

  body  = children.map(&:to_xml).join('')
  attrs = ''

  attributes.each do |attr|
    attrs << " #{attr.to_xml}"
  end

  if self_closing?
    return "<#{full_name}#{attrs} />"
  else
    return "<#{full_name}#{attrs}>#{body}</#{full_name}>"
  end
end

#unset(name) ⇒ Oga::XML::Attribute

Removes an attribute from the element.

Parameters:

  • name (String)

    The name (optionally including namespace prefix) of the attribute to remove.

Returns:



151
152
153
154
155
# File 'lib/oga/xml/element.rb', line 151

def unset(name)
  found = attribute(name)

  return attributes.delete(found) if found
end