Method: RubyXL::OOXMLObjectClassMethods#parse

Defined in:
lib/rubyXL/objects/ooxml_object.rb

#parse(node, known_namespaces = nil) ⇒ Object


114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/rubyXL/objects/ooxml_object.rb', line 114

def parse(node, known_namespaces = nil)
  case node
  when String, IO, Zip::InputStream then node = Nokogiri::XML.parse(node)
  end

  if node.is_a?(Nokogiri::XML::Document) then
    node = node.root
#        ignorable_attr = node.attributes['Ignorable']
#        @ignorables << ignorable_attr.value if ignorable_attr
  end

  obj = self.new
  hsh = {}
  node.namespace_definitions.each { |ns| hsh[ns.href] = ns.prefix }
  obj.local_namespaces = hsh

  known_attributes = obtain_class_variable(:@@ooxml_attributes)

  content_params = known_attributes['_']
  process_attribute(obj, node.text, content_params) if content_params

  node.attributes.each_pair { |attr_name, attr|
    attr_name = if attr.namespace then "#{attr.namespace.prefix}:#{attr.name}"
                else attr.name
                end

    attr_params = known_attributes[attr_name]

    next if attr_params.nil?
    # raise "Unknown attribute [#{attr_name}] for element [#{node.name}]" if attr_params.nil?
    process_attribute(obj, attr.value, attr_params) unless attr_params[:computed]
  }

  known_child_nodes = obtain_class_variable(:@@ooxml_child_nodes)

  unless known_child_nodes.empty?
    known_namespaces ||= obtain_class_variable(:@@ooxml_namespaces)

    node.element_children.each { |child_node|
      ns = child_node.namespace

      prefix = if known_namespaces.has_key?(ns&.href) then known_namespaces[ns&.href]
               else ns&.prefix
               end

      child_node_name = case prefix
                        when '', nil then child_node.name
                        else "#{prefix}:#{child_node.name}"
                        end

      child_node_params = known_child_nodes[child_node_name]
      raise "Unknown child node [#{child_node_name}] for element [#{node.name}]" if child_node_params.nil?
      parsed_object = child_node_params[:class].parse(child_node, known_namespaces)
      if child_node_params[:is_array] then
        index = parsed_object.index_in_collection

        collection = if (self < RubyXL::OOXMLContainerObject) then obj
                     else obj.send(child_node_params[:accessor])
                     end

        if index.nil? then
          collection << parsed_object
        else
          collection[index] = parsed_object
        end
      else
        obj.send("#{child_node_params[:accessor]}=", parsed_object)
      end
    }
  end

  obj
end