Class: Canon::Formatters::XmlFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/canon/formatters/xml_formatter.rb

Overview

XML formatter using Canonical XML 1.1 or pretty printing

Use this class for formatting XML documents for display or storage. For semantic comparison of XML documents, use Canon::Comparison instead.

XML Declaration Handling

  • Pretty printing (default): Preserves XML declaration

  • Canonicalization: Removes XML declaration (per W3C C14N 1.1 spec)

Usage

# Pretty print (preserves declaration)
Canon.format_xml(xml)

# Canonicalize (removes declaration)
Canon.format(xml, :xml, pretty: false)

For comparison, use:

Canon::Comparison.equivalent?(xml1, xml2, format: :xml)

Class Method Summary collapse

Class Method Details

.format(xml, pretty: true, indent: 2) ⇒ String

Format XML with pretty printing by default

Parameters:

  • xml (String)

    XML document to format

  • pretty (Boolean) (defaults to: true)

    Whether to pretty print (default: true)

  • indent (Integer) (defaults to: 2)

    Number of spaces for indentation (default: 2)

Returns:

  • (String)

    Formatted XML



37
38
39
40
41
42
43
# File 'lib/canon/formatters/xml_formatter.rb', line 37

def self.format(xml, pretty: true, indent: 2)
  if pretty
    Canon::PrettyPrinter::Xml.new(indent: indent).format(xml)
  else
    Canon::Xml::C14n.canonicalize(xml, with_comments: false)
  end
end

.parse(xml) ⇒ Nokogiri::XML::Document

Parse XML into a Nokogiri document

Parameters:

  • xml (String)

    XML document to parse

Returns:

  • (Nokogiri::XML::Document)

    Parsed XML document



48
49
50
51
52
# File 'lib/canon/formatters/xml_formatter.rb', line 48

def self.parse(xml)
  # Validate before parsing
  Canon::Validators::XmlValidator.validate!(xml)
  Nokogiri::XML(xml)
end