Class: CFPropertyList::NokogiriXMLParser

Inherits:
ParserInterface show all
Defined in:
lib/cfpropertylist/rbNokogiriParser.rb

Overview

XML parser

Constant Summary collapse

PARSER_OPTIONS =
Nokogiri::XML::ParseOptions::NOBLANKS|Nokogiri::XML::ParseOptions::NONET

Instance Method Summary collapse

Instance Method Details

#append_node(parent, child) ⇒ Object



68
69
70
# File 'lib/cfpropertylist/rbNokogiriParser.rb', line 68

def append_node(parent, child)
  parent << child
end

#load(opts) ⇒ Object

read a XML file

opts
  • :file - The filename of the file to load

  • :data - The data to parse



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/cfpropertylist/rbNokogiriParser.rb', line 13

def load(opts)
  doc = nil
  if(opts.has_key?(:file)) then
    File.open(opts[:file], "rb") { |fd| doc = Nokogiri::XML::Document.parse(fd, nil, nil, PARSER_OPTIONS) }
  else
    doc = Nokogiri::XML::Document.parse(opts[:data], nil, nil, PARSER_OPTIONS)
  end

  if doc
    root = doc.root.children.first
    return import_xml(root)
  end
rescue Nokogiri::XML::SyntaxError => e
  raise CFFormatError.new('invalid XML: ' + e.message)
end

#new_node(name) ⇒ Object



60
61
62
# File 'lib/cfpropertylist/rbNokogiriParser.rb', line 60

def new_node(name)
  @doc.create_element name
end

#new_text(val) ⇒ Object



64
65
66
# File 'lib/cfpropertylist/rbNokogiriParser.rb', line 64

def new_text(val)
  @doc.create_text_node val
end

#to_str(opts = {}) ⇒ Object

serialize CFPropertyList object to XML

opts = {}

Specify options: :formatted - Use indention and line breaks



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/cfpropertylist/rbNokogiriParser.rb', line 31

def to_str(opts={})
  doc = Nokogiri::XML::Document.new
  @doc = doc

  doc.root = doc.create_element 'plist', :version => '1.0'
  doc.encoding = 'UTF-8'

  doc.root << opts[:root].to_xml(self)

  # ugly hack, but there's no other possibility I know
  s_opts = Nokogiri::XML::Node::SaveOptions::AS_XML
  s_opts |= Nokogiri::XML::Node::SaveOptions::FORMAT if opts[:formatted]

  str = doc.serialize(:save_with => s_opts)
  str1 = String.new
  first = false
  str.each_line do |line|
    str1 << line
    unless(first) then
      str1 << "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" if line =~ /^\s*<\?xml/
    end

    first = true
  end

  str1.force_encoding('UTF-8') if str1.respond_to?(:force_encoding)
  return str1
end