Module: XmlConvert

Defined in:
lib/xml_convert.rb,
lib/xml_convert/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.decode_name(name) ⇒ String

Converts an encoded XML name to its original form.

Examples:

XmlConvert.decode_name('Order_x0020_Details') #=> 'Order Details'

Parameters:

  • name (String)

    the name to be decoded.

Returns:

  • (String)

    the decoded name.



11
12
13
14
15
16
17
18
19
20
# File 'lib/xml_convert.rb', line 11

def self.decode_name(name)
  return name if name.nil? || name.length == 0

  pos = name.index('_')
  return name if pos.nil? || pos + 6 >= name.length

  return name if name[pos+1] != 'x' || name[pos+6] != '_'

  name.slice(0, pos) << try_decoding(name[pos+1..-1])
end

.encode_local_name(name) ⇒ String

Converts the name to a valid XML local name.

Examples:

XmlConvert.encode_local_name('a:b') #=> 'a_x003a_b'

XmlConvert.encode_name('Order Details') #=> 'Order_x0020_Details'

Parameters:

  • name (String)

    the name to be encoded.

Returns:

  • (String)

    the encoded name.



49
50
51
# File 'lib/xml_convert.rb', line 49

def self.encode_local_name(name)
  encode_name(name).gsub(':', '_x003a_')
end

.encode_name(name) ⇒ String

Converts the name to a valid XML name.

Examples:

XmlConvert.encode_name('Order Details') #=> 'Order_x0020_Details'

Parameters:

  • name (String)

    the name to be encoded.

Returns:

  • (String)

    the encoded name.



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/xml_convert.rb', line 28

def self.encode_name(name)
  return name if name.nil? || name.length == 0

  name.chars.each_with_index.reduce("") do |memo, (c, i)|
    if is_invalid?(c, memo == "")
      memo << "_x#{'%04x' % c.ord}_"
    elsif c == '_' && i+6 < name.length && name[i+1] == 'x' && name[i+6] == '_'
      memo << '_x005f_'
    else
      memo << c
    end
  end
end