Method: REXML::Element#attribute

Defined in:
lib/rexml/element.rb

#attribute(name, namespace = nil) ⇒ Object

:call-seq:

attribute(name, namespace = nil)

Returns the string value for the given attribute name.

With only argument name given, returns the value of the named attribute if it exists, otherwise nil:

xml_string = "  <root xmlns=\"ns0\">\n    <a xmlns=\"ns1\" attr=\"value\"></a>\n    <b xmlns=\"ns2\" attr=\"value\"></b>\n    <c attr=\"value\"/>\n </root>\n"
d = REXML::Document.new(xml_string)
root = d.root
a = root[1] # => <a xmlns='ns1' attr='value'/>
a.attribute('attr') # => attr='value'
a.attribute('nope') # => nil

With arguments name and namespace given, returns the value of the named attribute if it exists, otherwise nil:

xml_string = "<root xmlns:a='a' a:x='a:x' x='x'/>"
document = REXML::Document.new(xml_string)
document.root.attribute("x")      # => x='x'
document.root.attribute("x", "a") # => a:x='a:x'


1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
# File 'lib/rexml/element.rb', line 1279

def attribute( name, namespace=nil )
  prefix = namespaces.key(namespace) if namespace
  prefix = nil if prefix == 'xmlns'

  ret_val =
    attributes.get_attribute( prefix ? "#{prefix}:#{name}" : name )

  return ret_val unless ret_val.nil?
  return nil if prefix.nil?

  # now check that prefix'es namespace is not the same as the
  # default namespace
  return nil unless ( namespaces[ prefix ] == namespaces[ 'xmlns' ] )

  attributes.get_attribute( name )
end