1. Yuji Hanamura
  2. XmlFormatter4JR

Commits

Yuji Hanamura  committed eeaf0ce

XML formatter for JRuby project.

  • Participants
  • Branches default

Comments (0)

Files changed (3)

File .hgignore

View file
+syntax: glob
+*~
+
+syntax: regexp
+

File test_xmlformatter.rb

View file
+require 'test/unit'
+require 'xmlformatter'
+
+
+class TC_XmlFormatter < Test::Unit::TestCase
+  def setup
+  end
+
+  def test_format_xml_empty_tag
+    assert_equal(format_xml("<test></test>"), "<test/>")
+  end
+
+  def test_format_xml_text_node
+    assert_equal(format_xml("<test>text</test>"), "<test>text</test>")
+  end
+
+  def test_format_xml_child_empty_node
+    assert_equal(format_xml("<test><child></child></test>"), "<test>\n  <child/>\n</test>")
+  end
+
+  def test_format_xml_child_text_node
+    assert_equal(format_xml("<test><child>text</child></test>"), "<test>\n  <child>text</child>\n</test>")
+  end
+
+  def test_format_xml_child_child_node
+    assert_equal(format_xml("<test><child><child2>text</child2></child></test>"), "<test>\n  <child>\n    <child2>text</child2>\n  </child>\n</test>")
+  end
+
+  def test_format_xml_sibling_node
+    assert_equal(format_xml("<test><sibling1>text</sibling1><sibling2></sibling2></test>"), "<test>\n  <sibling1>text</sibling1>\n  <sibling2/>\n</test>")
+  end
+
+  def test_format_xml_xml_declaration
+    assert_equal(format_xml("<?xml version='1.0'?><test><sibling1>text</sibling1><sibling2></sibling2></test>"), "<?xml version='1.0'?>\n<test>\n  <sibling1>text</sibling1>\n  <sibling2/>\n</test>")
+  end
+end

File xmlformatter.rb

View file
+require 'rexml/document'
+require 'rexml/formatters/pretty'
+
+
+=begin
+If +format+ is true, return the formatted xml string.
+Else, return the xml string.
+=end
+def format_xml(in_xml, indent=2)
+  doc = REXML::Document.new(in_xml)
+  if indent > 0
+    formatter = REXML::Formatters::Pretty.new(indent)
+    formatter.compact = true
+  else
+    raise "require indent is greater than 0. #{indent} is not greater than 0."
+  end
+  out_xml = ""
+  formatter.write(doc, out_xml)
+  return out_xml
+end
+
+
+if __FILE__ == $0
+  xml = ""
+  ARGF.each do |line| xml += line end
+
+  out_xml = format_xml(xml)
+  puts out_xml
+end