### Ruby: Installation using Gem
Source: https://github.com/ohler55/ox/wiki/README
Standard command to install the Ox gem using RubyGems package manager. This command fetches and installs the latest stable version of the Ox gem and its dependencies.
```ruby
gem install ox
```
--------------------------------
### Ox File I/O Operations
Source: https://context7.com/ohler55/ox/llms.txt
Illustrates how to write Ruby objects or XML documents to files and read them back using Ox. Includes examples for writing, reading with generic mode, and SAX parsing from files.
```ruby
require 'ox'
# Write to file
doc = Ox::Document.new(version: '1.0')
root = Ox::Element.new('config')
root << Ox::Element.new('setting').tap { |e| e[:name] = 'debug'; e << 'true' }
doc << root
Ox.to_file('/tmp/config.xml', doc, indent: 2)
# Read from file
loaded_doc = Ox.load_file('/tmp/config.xml', mode: :generic)
puts loaded_doc.root.setting.text # => "true"
# SAX parse from file
class FileHandler < Ox::Sax
def start_element(name)
puts "Found element: #{name}"
end
end
File.open('/tmp/config.xml', 'r') do |f|
Ox.sax_parse(FileHandler.new, f)
end
```
--------------------------------
### Ox XML Encoding: Hash Example
Source: https://github.com/ohler55/ox/wiki/README
Shows the XML encoding for a Hash in Ox. The 'h' element denotes a Hash, containing pairs of key-value elements. Each pair consists of the key's XML representation followed by the value's XML representation.
```xml
1
one
2
two
```
--------------------------------
### Ox XML Encoding: Fixnum Example
Source: https://github.com/ohler55/ox/wiki/README
Demonstrates how a Fixnum (integer) is encoded in the Ox XML format. The type indicator 'i' is used for Fixnum, with the integer value as the element's text content.
```xml
123
```
--------------------------------
### Ox XML Encoding: Array Example
Source: https://github.com/ohler55/ox/wiki/README
Illustrates the XML representation of an Array in Ox. The 'a' element signifies an array, and its sub-elements represent the array's contents, which can be of various types (e.g., 'i' for Fixnum, 's' for String).
```xml
1
abc
```
--------------------------------
### Construct and Write Generic XML Documents
Source: https://github.com/ohler55/ox/blob/develop/README.md
Shows how to build an XML document structure programmatically using Ox::Document and Ox::Element, including support for instructions, CDATA, comments, and raw injection.
```ruby
require 'ox'
doc = Ox::Document.new
instruct = Ox::Instruct.new(:xml)
instruct[:version] = '1.0'
instruct[:encoding] = 'UTF-8'
instruct[:standalone] = 'yes'
doc << instruct
top = Ox::Element.new('top')
top[:name] = 'sample'
doc << top
mid = Ox::Element.new('middle')
mid[:name] = 'second'
top << mid
bot = Ox::Element.new('bottom')
bot[:name] = 'third'
bot << 'text at bottom'
mid << bot
other_elements = Ox::Element.new('otherElements')
other_elements << Ox::CData.new('John Smith')
other_elements << Ox::Comment.new('Director\'s commentary')
other_elements << Ox::Raw.new('Be carefull with this! Direct inject into XML!')
top << other_elements
xml = Ox.dump(doc)
```
--------------------------------
### Manage XML Documents with Ox::Document
Source: https://context7.com/ohler55/ox/llms.txt
Shows how to construct a full XML document including prolog attributes and nested elements.
```ruby
require 'ox'
# Create document with prolog
doc = Ox::Document.new(version: '1.0', encoding: 'UTF-8')
# Add elements
root = Ox::Element.new('catalog')
doc << root
item = Ox::Element.new('item')
item[:id] = '1'
item << 'First item'
root << item
xml = Ox.dump(doc)
```
--------------------------------
### Create and Define Ox Bag Objects
Source: https://context7.com/ohler55/ox/llms.txt
Demonstrates how to create a Bag object with initial values and define dynamic classes based on Bag. Bag objects allow for attribute access similar to Ruby objects.
```ruby
require 'ox'
# Create Bag with initial values
bag = Ox::Bag.new(:@name => 'test', :@value => 42)
puts bag.name # => "test"
puts bag.value # => 42
# Define dynamic class based on Bag
MyClass = Ox::Bag.define_class('MyModule::MyClass')
obj = MyClass.new(:@x => 10, :@y => 20)
puts obj.x # => 10
puts obj.y # => 20
puts obj.class # => MyModule::MyClass
```
--------------------------------
### XML Processing Instructions (Instruct) in Ruby
Source: https://context7.com/ohler55/ox/llms.txt
Illustrates how to create and manage XML processing instructions using Ox::Instruct. This includes generating the standard XML declaration with version and encoding attributes, as well as custom processing instructions like stylesheet links.
```ruby
require 'ox'
doc = Ox::Document.new
xml_instruct = Ox::Instruct.new(:xml)
xml_instruct[:version] = '1.0'
xml_instruct[:encoding] = 'UTF-8'
doc << xml_instruct
stylesheet = Ox::Instruct.new(:'xml-stylesheet')
stylesheet[:type] = 'text/xsl'
stylesheet[:href] = 'transform.xsl'
doc << stylesheet
root = Ox::Element.new('data')
doc << root
xml = Ox.dump(doc)
```
--------------------------------
### Create and Append XML Elements in Ruby
Source: https://context7.com/ohler55/ox/llms.txt
Demonstrates how to create new XML elements, set attributes, append text content, and add them as children to a root element using the Ox library. It also shows how to access child elements and their attributes using a fluent API.
```ruby
require 'ox'
root = Ox::Element.new('root')
item1 = Ox::Element.new('item')
item1[:id] = '1'
item1[:category] = 'books'
item1 << 'Ruby Programming'
root << item1
item2 = Ox::Element.new('item')
item2[:id] = '2'
item2[:category] = 'software'
item2 << 'XML Parser'
root << item2
puts root.item.text # => "Ruby Programming"
puts root.item(1).text # => "XML Parser"
puts root.item.id # => "1"
puts root.item.category # => "books"
puts root.locate('item') # => [item1, item2]
puts root.locate('item[0]') # => [item1]
puts root.locate('item[@category=books]') # => [item1]
puts root.locate('item/@id') # => ["1", "2"]
puts root.locate('*/@category') # => ["books", "software"]
root.each('item') { |item| puts item.text }
root.remove_children_by_path('item[@id=1]')
```
--------------------------------
### Ruby: Generic XML Document Creation, Parsing, and Dumping with Ox
Source: https://github.com/ohler55/ox/wiki/README
Illustrates the creation of an XML document structure using Ox::Document and Ox::Element, followed by dumping it to an XML string with Ox.dump() and parsing it back into a document object with Ox.parse(). This showcases Ox's capabilities as a generic XML parser and writer.
```ruby
require 'ox'
doc = Ox::Document.new(:version => '1.0')
top = Ox::Element.new('top')
top[:name] = 'sample'
doc << top
mid = Ox::Element.new('middle')
mid[:name] = 'second'
top << mid
bot = Ox::Element.new('bottom')
bot[:name] = 'third'
mid << bot
xml = Ox.dump(doc)
puts xml
doc2 = Ox.parse(xml)
puts "Same? #{doc == doc2}"
```
--------------------------------
### Configure Ox Global Default Options
Source: https://context7.com/ohler55/ox/llms.txt
Shows how to view and set global default parsing and dumping options for the Ox library. Options include parsing mode, effort level, encoding, and indentation.
```ruby
require 'ox'
# View current defaults
puts Ox.default_options
# Set defaults for tolerant HTML parsing
Ox.default_options = {
mode: :generic, # :generic, :object, :hash, :hash_no_attrs
effort: :tolerant, # :strict, :tolerant, :auto
smart: true, # HTML smart mode
symbolize_keys: true, # Use Symbol keys in hash mode
indent: 2, # Indentation spaces for dump
with_xml: true, # Include XML declaration
encoding: 'UTF-8', # Output encoding
circular: false, # Handle circular references
skip: :skip_white # Skip whitespace in SAX parsing
}
# Parse with defaults
doc = Ox.load('
Text') # Tolerant mode handles unclosed tags
```
--------------------------------
### Ruby: Object Serialization and Deserialization with Ox
Source: https://github.com/ohler55/ox/wiki/README
Demonstrates how to serialize a Ruby object into an XML string using Ox.dump() and deserialize it back into an object using Ox.parse_obj(). This method is faster than Ruby's Marshal and produces human-readable XML.
```ruby
require 'ox'
class Sample
attr_accessor :a, :b, :c
def initialize(a, b, c)
@a = a
@b = b
@c = c
end
end
# Create Object
obj = Sample.new(1, "bee", ['x', :y, 7.0])
# Now dump the Object to an XML String.
xml = Ox.dump(obj)
# Convert the object back into a Sample Object.
obj2 = Ox.parse_obj(xml)
```
--------------------------------
### Quick Parse Methods with Ox.parse and Ox.parse_obj
Source: https://context7.com/ohler55/ox/llms.txt
Convenience methods for rapid XML parsing into documents or deserializing objects back into Ruby instances.
```ruby
require 'ox'
# Parse XML to Ox::Document
xml = 'Peter'
doc = Ox.parse(xml)
# Deserialize object from XML
obj2 = Ox.parse_obj(xml)
```
--------------------------------
### Ox.parse / Ox.parse_obj - Quick Parsing Methods
Source: https://context7.com/ohler55/ox/llms.txt
Convenience methods for quickly parsing XML strings into Ox::Document or Ruby objects.
```APIDOC
## Ox.parse / Ox.parse_obj - Quick Parsing Methods
### Description
Convenience methods for parsing XML strings. `Ox.parse` returns an Ox::Document in generic mode, while `Ox.parse_obj` deserializes XML back into Ruby objects.
### Method
`Ox.parse(xml_string)`
`Ox.parse_obj(xml_string)`
### Parameters
- **xml_string** (String) - The XML string to parse.
### Request Example (Ox.parse)
```ruby
require 'ox'
# Parse XML to Ox::Document
xml = 'Peter'
doc = Ox.parse(xml)
puts doc.root.name # => "People"
```
### Request Example (Ox.parse_obj)
```ruby
require 'ox'
class Sample
attr_accessor :a, :b
def initialize(a=nil, b=nil)
@a = a
@b = b
end
end
obj = Sample.new(42, "hello")
xml = Ox.dump(obj, mode: :object)
obj2 = Ox.parse_obj(xml)
puts obj2.a # => 42
puts obj2.b # => "hello"
```
### Response Example
- **Ox.parse**: Returns an `Ox::Document` object.
- **Ox.parse_obj**: Returns a deserialized Ruby object.
```
--------------------------------
### Implement SAX XML Parsing
Source: https://github.com/ohler55/ox/blob/develop/README.md
Demonstrates how to create a custom SAX handler by inheriting from Ox::Sax. This approach allows for event-driven parsing of XML documents, which is useful for processing large files without loading them entirely into memory.
```ruby
require 'stringio'
require 'ox'
class Sample < ::Ox::Sax
def start_element(name); puts "start: #{name}"; end
def end_element(name); puts "end: #{name}"; end
def attr(name, value); puts " #{name} => #{value}"; end
def text(value); puts "text #{value}"; end
end
io = StringIO.new(%{
})
handler = Sample.new()
Ox.sax_parse(handler, io)
```
--------------------------------
### Yield SAX Results Immediately
Source: https://github.com/ohler55/ox/blob/develop/README.md
Shows how to pass a block or proc to a SAX handler to process XML elements as they are encountered during parsing. This allows for immediate action on parsed data.
```ruby
require 'stringio'
require 'ox'
class Yielder < ::Ox::Sax
def initialize(block); @yield_to = block; end
def start_element(name); @yield_to.call(name); end
end
io = StringIO.new(%{
})
proc = Proc.new { |name| puts name }
handler = Yielder.new(proc)
Ox.sax_parse(handler, io)
```
--------------------------------
### Parse XML with Ox.load
Source: https://context7.com/ohler55/ox/llms.txt
Demonstrates parsing XML strings into Ruby objects using various modes like generic, hash, and object serialization. It supports different output formats based on the mode parameter.
```ruby
require 'ox'
xml = %{
Peter
Ohler
John
Doe
}
# Generic mode - returns Ox::Document
doc = Ox.load(xml, mode: :generic)
root = doc.root
puts root.name
puts root.Person.given.text
# Hash mode - returns nested Hash
hash = Ox.load(xml, mode: :hash)
# Hash without attributes
hash = Ox.load(xml, mode: :hash_no_attrs)
```
--------------------------------
### Serialize Objects to XML with Ox.dump
Source: https://context7.com/ohler55/ox/llms.txt
Converts Ruby objects or Ox document structures into XML strings. Supports object serialization and generic XML document generation.
```ruby
require 'ox'
# Create and dump an Ox::Document
doc = Ox::Document.new
instruct = Ox::Instruct.new(:xml)
instruct[:version] = '1.0'
doc << instruct
top = Ox::Element.new('top')
doc << top
xml = Ox.dump(doc)
# Dump Ruby object to XML
class Sample
attr_accessor :a, :b, :c
def initialize(a, b, c)
@a = a
@b = b
@c = c
end
end
obj = Sample.new(1, "bee", ['x', :y, 7.0])
xml = Ox.dump(obj, mode: :object)
```
--------------------------------
### Configure Ox for HTML Parsing
Source: https://github.com/ohler55/ox/blob/develop/README.md
Sets the default options for the Ox parser to handle HTML content, which is often less strictly formatted than XML. It uses the generic mode with tolerant effort and smart parsing enabled.
```ruby
Ox.default_options = {
mode: :generic,
effort: :tolerant,
smart: true
}
```
--------------------------------
### SAX XML Streaming Parser in Ruby
Source: https://context7.com/ohler55/ox/llms.txt
Implements a high-performance SAX streaming parser for large XML files. It defines a handler class with callback methods invoked during parsing to process elements, attributes, and text content. Options like symbolize, convert_special, skip, and strip_namespace can be configured.
```ruby
require 'ox'
require 'stringio'
class MySaxHandler < Ox::Sax
def initialize
@elements = []
@attributes = {}
end
attr_reader :elements, :attributes
def start_element(name)
@elements << name
end
def end_element(name)
# Called when element closes
end
def attr(name, value)
@attributes[name] = value
end
def text(value)
puts "Text content: #{value}"
end
def cdata(value)
puts "CDATA: #{value}"
end
def comment(value)
puts "Comment: #{value}"
end
end
xml = %{
The Great Novel
Jane Doe
Ruby Mastery
John Smith
}
handler = MySaxHandler.new
Ox.sax_parse(handler, StringIO.new(xml), {
symbolize: true,
convert_special: true,
skip: :skip_white,
strip_namespace: true
})
puts handler.elements
puts handler.attributes
```
--------------------------------
### Ox::Document - XML Document Container
Source: https://context7.com/ohler55/ox/llms.txt
Represents a complete XML document, including prolog attributes and child elements.
```APIDOC
## Ox::Document - XML Document Container
### Description
Represents a complete XML document with prolog attributes (version, encoding, standalone). Contains elements as child nodes and provides access to the root element.
### Initialization
`Ox::Document.new(options)`
### Parameters
- **options** (Hash) - Optional. Attributes for the XML prolog:
- **version** (String) - XML version (e.g., '1.0').
- **encoding** (String) - XML encoding (e.g., 'UTF-8').
- **standalone** (String) - 'yes' or 'no'.
### Methods
- **`<< element`**: Appends an `Ox::Element` to the document.
- **`root`**: Returns the root `Ox::Element` of the document.
### Request Example
```ruby
require 'ox'
# Create document with prolog
doc = Ox::Document.new(version: '1.0', encoding: 'UTF-8', standalone: 'yes')
# Add elements
root = Ox::Element.new('catalog')
doc << root
item = Ox::Element.new('item')
item[:id] = '1'
item << 'First item'
root << item
# Access root element
puts doc.root.name # => "catalog"
puts doc.root.item.text # => "First item"
xml = Ox.dump(doc)
#
#
# - First item
#
```
### Response Example
```ruby
# Ox::Document object
```
```
--------------------------------
### Serialize and Deserialize Ruby Objects to XML
Source: https://context7.com/ohler55/ox/llms.txt
Demonstrates using Ox in object mode to serialize Ruby objects into XML and deserialize them back. This supports complex object graphs, including nested objects, arrays, hashes, and circular references.
```ruby
require 'ox'
class Person
attr_accessor :name, :age, :friends
def initialize(name=nil, age=nil)
@name = name
@age = age
@friends = []
end
def to_s
"#{@name} (#{@age})"
end
end
# Create object graph
alice = Person.new('Alice', 30)
bob = Person.new('Bob', 25)
alice.friends << bob
# Serialize to XML
xml = Ox.dump(alice, mode: :object, circular: true, with_xml: true)
puts xml
# Deserialize back to Ruby
restored = Ox.load(xml, mode: :object)
puts restored.name # => "Alice"
puts restored.age # => 30
puts restored.friends[0].name # => "Bob"
# Works with built-in types too
data = {
numbers: [1, 2, 3],
nested: { key: :value },
time: Time.now,
regex: /pattern/i
}
xml = Ox.dump(data, mode: :object)
restored_data = Ox.load(xml, mode: :object)
```
--------------------------------
### HTML SAX Streaming Parser in Ruby
Source: https://context7.com/ohler55/ox/llms.txt
Provides a SAX streaming parser specifically for HTML, offering tolerance for malformed markup. It uses built-in hints for common HTML elements and gracefully handles unclosed tags and self-closing tags.
```ruby
require 'ox'
class HtmlHandler < Ox::Sax
def initialize
@tags = []
end
attr_reader :tags
def start_element(name)
@tags << name
end
def text(value)
puts "Content: #{value.strip}" unless value.strip.empty?
end
end
html = %{
Test Page
First paragraph
Second paragraph
}
handler = HtmlHandler.new
Ox.sax_html(handler, html)
puts handler.tags
```
--------------------------------
### Ox.load - Parse XML String
Source: https://context7.com/ohler55/ox/llms.txt
Parses an XML string into Ruby objects using various modes like :generic, :object, :hash, and :hash_no_attrs.
```APIDOC
## Ox.load - Parse XML String
### Description
The primary method to parse XML into Ruby objects. Supports multiple modes: `:generic` returns Ox::Document, `:object` deserializes Ruby objects, `:hash` converts to nested hashes, and `:hash_no_attrs` converts to hashes without attributes.
### Method
`Ox.load(xml_string, options)`
### Parameters
- **xml_string** (String) - The XML string to parse.
- **options** (Hash) - Optional. Configuration for parsing:
- **mode** (:generic, :object, :hash, :hash_no_attrs) - Specifies the parsing mode. Defaults to `:generic`.
- **symbolize_keys** (Boolean) - If true, hash keys will be Symbols. Defaults to true for `:hash` mode.
### Request Example
```ruby
require 'ox'
xml = %{
Peter
Ohler
John
Doe
}
# Generic mode - returns Ox::Document
doc = Ox.load(xml, mode: :generic)
puts doc.root.name # => "People"
puts doc.root.Person.given.text # => "Peter"
puts doc.root.Person.age # => "58"
puts doc.root.Person(1).given.text # => "John"
# Hash mode - returns nested Hash with Symbol keys
hash = Ox.load(xml, mode: :hash)
# => {:People=>[{:Person=>[{:age=>"58"}, {:given=>"Peter"}, {:surname=>"Ohler"}]}, ...]}
# Hash with String keys
hash = Ox.load(xml, mode: :hash, symbolize_keys: false)
# Hash without attributes
hash = Ox.load(xml, mode: :hash_no_attrs)
# => {:People=>{:Person=>{:given=>"Peter", :surname=>"Ohler"}}}
```
### Response Example (Generic Mode)
```ruby
# Ox::Document object representing the XML structure
```
### Response Example (Hash Mode)
```ruby
# Hash object representing the XML structure
```
```
--------------------------------
### Ox.dump - Serialize to XML String
Source: https://context7.com/ohler55/ox/llms.txt
Converts Ruby objects or Ox documents to XML strings, supporting :object and :generic modes.
```APIDOC
## Ox.dump - Serialize to XML String
### Description
Converts Ruby objects or Ox documents to XML strings. Supports `:object` mode for Ruby Object serialization and `:generic` mode for Ox::Document output.
### Method
`Ox.dump(data, options)`
### Parameters
- **data** (Ox::Document, Ox::Element, Object) - The data to serialize to XML.
- **options** (Hash) - Optional. Configuration for dumping:
- **mode** (:object, :generic) - Specifies the serialization mode. Defaults to `:generic` for Ox::Document/Element, and `:object` for other Ruby objects.
### Request Example (Ox::Document)
```ruby
require 'ox'
# Create and dump an Ox::Document
doc = Ox::Document.new
instruct = Ox::Instruct.new(:xml)
instruct[:version] = '1.0'
instruct[:encoding] = 'UTF-8'
doc << instruct
top = Ox::Element.new('top')
top[:name] = 'sample'
doc << top
mid = Ox::Element.new('middle')
mid[:name] = 'second'
top << mid
bot = Ox::Element.new('bottom')
bot[:name] = 'third'
bot << 'text at bottom'
mid << bot
xml = Ox.dump(doc)
#
#
#
# text at bottom
#
#
```
### Request Example (Ruby Object)
```ruby
require 'ox'
class Sample
attr_accessor :a, :b, :c
def initialize(a, b, c)
@a = a
@b = b
@c = c
end
end
obj = Sample.new(1, "bee", ['x', :y, 7.0])
xml = Ox.dump(obj, mode: :object)
# 1beexy7.0
```
### Response Example
```ruby
# XML string representation of the input data
```
```
--------------------------------
### Special XML Node Types (CDATA, Comment, Raw) in Ruby
Source: https://context7.com/ohler55/ox/llms.txt
Demonstrates the usage of special XML node types provided by Ox: CDATA for preserving content without escaping, Comment for adding XML comments, and Raw for injecting raw XML fragments. These nodes can be appended as children to Element nodes.
```ruby
require 'ox'
doc = Ox::Document.new(version: '1.0')
root = Ox::Element.new('container')
doc << root
cdata = Ox::CData.new('')
root << cdata
comment = Ox::Comment.new('This is a comment')
root << comment
raw = Ox::Raw.new('')
root << raw
xml = Ox.dump(doc)
```
--------------------------------
### Parse XML into Ruby Hash
Source: https://github.com/ohler55/ox/blob/develop/README.md
Converts XML data directly into a Ruby Hash structure. It supports different modes, such as including or excluding attributes, providing a fast way to access XML data as native Ruby objects.
```ruby
require 'ox'
xml = %{
Rock bottom
}
puts Ox.load(xml, mode: :hash)
puts Ox.load(xml, mode: :hash_no_attrs)
```
--------------------------------
### Ox::Element - XML Element Node
Source: https://context7.com/ohler55/ox/llms.txt
Represents an XML element with name, attributes, and child nodes, supporting easy access and XPath-like queries.
```APIDOC
## Ox::Element - XML Element Node
### Description
Represents an XML element with name, attributes, and child nodes. Supports the "easy" API for accessing sub-elements and attributes by name, plus the `locate()` method for XPath-like queries.
### Initialization
`Ox::Element.new(name, attributes = {})`
### Parameters
- **name** (String) - The name of the XML element.
- **attributes** (Hash) - Optional. A hash of attributes for the element.
### Methods
- **`[]=(key, value)`**: Sets an attribute.
- **`[](key)`**: Gets an attribute value.
- **`<< node`**: Appends a child node (element, text, etc.).
- **`locate(path)`**: Performs an XPath-like query to find nodes.
- **`text`**: Returns the text content of the element (if it's a text node or has one).
### Request Example
```ruby
require 'ox'
# Create elements
root = Ox::Element.new('catalog')
root[:version] = '2.0'
item = Ox::Element.new('item')
item[:id] = '1'
item << 'First item'
root << item
# Accessing elements and attributes
puts root.name # => "catalog"
puts root.version # => "2.0"
puts root.item.text # => "First item"
puts root.locate('item').first.text # => "First item"
# Dumping the element to XML
xml = Ox.dump(root)
#
# - First item
#
```
### Response Example
```ruby
# Ox::Element object
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.