self-close certain XML/HTML elements.

When an XML element has no child nodes a self-closing tag is used. When parsing
documents/elements in HTML mode this is only done if the element is a so called
"void element" (e.g. <link> tags).

This fixes #46.
This commit is contained in:
Yorick Peterse committed 2014-09-16 00:44:38 +02:00
1 parent 6fc7e2e254
commit 32b11ef1e2
5 files changed
+106 -33

No files matched your search

+1
View File
@@ -18,6 +18,7 @@ if RUBY_PLATFORM == 'java'
end
#:nocov:
require_relative 'oga/xml/html_void_elements'
require_relative 'oga/xml/querying'
require_relative 'oga/xml/traversal'
require_relative 'oga/xml/node'
+28 -2
View File
@@ -211,7 +211,12 @@ module Oga
# @return [String]
#
def to_xml
ns = namespace_name ? "#{namespace_name}:" : ''
if namespace_name
full_name = "#{namespace_name}:#{name}"
else
full_name = name
end
body = children.map(&:to_xml).join('')
attrs = ''
@@ -219,7 +224,11 @@ module Oga
attrs << " #{attr.to_xml}"
end
return "<#{ns}#{name}#{attrs}>#{body}</#{ns}#{name}>"
if self_closing?
return "<#{full_name}#{attrs} />"
else
return "<#{full_name}#{attrs}>#{body}</#{full_name}>"
end
end
##
@@ -278,6 +287,23 @@ module Oga
return merged
end
##
# Returns `true` if the element is a self-closing element.
#
# @return [TrueClass|FalseClass]
#
def self_closing?
self_closing = children.empty?
root = root_node
if root.is_a?(Document) and root.type == :html \
and !HTML_VOID_ELEMENTS.include?(name)
self_closing = false
end
return self_closing
end
private
##
+28
View File
@@ -0,0 +1,28 @@
module Oga
module XML
##
# Names of the HTML void elements that should be handled when HTML lexing
# is enabled.
#
# @return [Set]
#
HTML_VOID_ELEMENTS = Set.new([
'area',
'base',
'br',
'col',
'command',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr'
])
end # XML
end # Oga
-25
View File
@@ -40,31 +40,6 @@ module Oga
class Lexer
attr_reader :html
##
# Names of the HTML void elements that should be handled when HTML lexing
# is enabled.
#
# @return [Set]
#
HTML_VOID_ELEMENTS = Set.new([
'area',
'base',
'br',
'col',
'command',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr'
])
##
# @param [String|IO] data The data to lex. This can either be a String or
# an IO instance.