Class: Oga::XML::Document

Inherits:
Object
  • Object
show all
Includes:
Querying, Traversal
Defined in:
lib/oga/xml/document.rb

Overview

Class used for storing information about an entire XML document. This includes the doctype, XML declaration, child nodes and more.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Traversal

#each_node

Methods included from Querying

#at_css, #at_xpath, #css, #xpath

Constructor Details

#initialize(options = {}) ⇒ Document

Returns a new instance of Document.

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):



29
30
31
32
33
34
35
# File 'lib/oga/xml/document.rb', line 29

def initialize(options = {})
  @doctype         = options[:doctype]
  @xml_declaration = options[:xml_declaration]
  @type            = options[:type] || :xml

  self.children = options[:children] if options[:children]
end

Instance Attribute Details

#doctypeOga::XML::Doctype

Returns:



12
13
14
# File 'lib/oga/xml/document.rb', line 12

def doctype
  @doctype
end

#typeSymbol (readonly)

The document type, either :xml or :html.

Returns:

  • (Symbol)


19
20
21
# File 'lib/oga/xml/document.rb', line 19

def type
  @type
end

#xml_declarationOga::XML::XmlDeclaration



15
16
17
# File 'lib/oga/xml/document.rb', line 15

def xml_declaration
  @xml_declaration
end

Instance Method Details

#childrenOga::XML::NodeSet

Returns:



40
41
42
# File 'lib/oga/xml/document.rb', line 40

def children
  @children ||= NodeSet.new([], self)
end

#children=(nodes) ⇒ Object

Sets the child nodes of the document.

Parameters:



49
50
51
52
53
54
55
# File 'lib/oga/xml/document.rb', line 49

def children=(nodes)
  if nodes.is_a?(NodeSet)
    @children = nodes
  else
    @children = NodeSet.new(nodes, self)
  end
end

#html?TrueClass|FalseClass

Returns:

  • (TrueClass|FalseClass)


79
80
81
# File 'lib/oga/xml/document.rb', line 79

def html?
  type.equal?(:html)
end

#inspectString

Inspects the document and its child nodes. Child nodes are indented for each nesting level.

Returns:

  • (String)


89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/oga/xml/document.rb', line 89

def inspect
  segments = []

  [:doctype, :xml_declaration, :children].each do |attr|
    value = send(attr)

    if value
      segments << "#{attr}: #{value.inspect}"
    end
  end

  <<-EOF.strip
Document(
  #{segments.join("\n  ")}
)
  EOF
end

#to_xmlString

Converts the document and its child nodes to XML.

Returns:

  • (String)


62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/oga/xml/document.rb', line 62

def to_xml
  xml = children.map(&:to_xml).join('')

  if doctype
    xml = doctype.to_xml + "\n" + xml.strip
  end

  if xml_declaration
    xml = xml_declaration.to_xml + "\n" + xml.strip
  end

  xml
end