Manually Creating Documents
Besides being able to parse documents, Oga also allows you to create documents manually. This can be useful if you want to dynamically generate XML/HTML.
Documents can be greated in two ways:
- Full blown documents (using )
- XML fragments (using just and the likes)
For example, lets create a document with a specific encoding and a single element:
xml_decl = ::::.(:encoding => 'UTF-16') document = ::::.(:xml_declaration => xml_decl) element = ::::.(:name => 'example') document.children << element
If you now serialize this back to XML (by calling
document.to_xml) you’d get
the following XML:
<?xml version="1.0" encoding="UTF-16" ?> <example />
You can also serialize elements on their own:
This would output:
The easiest way to add (or remove) attributes is by usingand . For example, to add an attribute:
element = ::::.(:name => 'example') element.set('class', 'foo') element.to_xml # => "<example class=\"foo\" />"
And to remove an attribute:
Modifying text of elements can be done in two ways:
- Adding instances to the list of child nodes of an instance
The second option is the easiest and recommended way of doing this. Usage is quite simple:
element = Oga::XML::Element.new(:name => 'p') element.inner_text = 'Hello' element.to_xml => "<p>Hello</p>"
Special characters such as
< are escaped automatically when calling