Module: XmlParser

Defined in:
lib/xmlutils/xml_doc.rb

Class Method Summary collapse

Class Method Details

.build_xmlnode(element, parent = nil) ⇒ Object



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/xmlutils/xml_doc.rb', line 250

def self.build_xmlnode(element, parent = nil)
  attrs = {}
  element.attributes.each do |k, attr|
    attrs[k.to_sym] = attr.value
  end

  ns = element.namespace(element.prefix)
  attrs[:namespace] = ns if ns && !ns.empty?

  text_content = element.children
    .select { |c| c.is_a?(XmlUtils::Text) || c.is_a?(XmlUtils::CData) }
    .map(&:to_s)
    .join
  attrs[:text] = text_content unless text_content.strip.empty?

  node = XmlNode.new(name: element.name, parent: parent, attributes: attrs)

  element.children.select { |c| c.is_a?(XmlUtils::Element) }.each do |child|
    build_xmlnode(child, node)
  end

  node
end

.load(filepath) ⇒ Object



236
237
238
# File 'lib/xmlutils/xml_doc.rb', line 236

def self.load(filepath)
  return File.exist?(filepath) ? XmlParser.parse(File.read(filepath)) : nil
end

.parse(s) ⇒ Object



240
241
242
243
244
245
246
# File 'lib/xmlutils/xml_doc.rb', line 240

def self.parse(s)
  doc = XmlUtils.parse(s)
  root_elem = doc.root
  return nil unless root_elem
  
  build_xmlnode(root_elem)
end