File handling XML DOM

XML with DOM

The klyn.io.xml.dom package parses XML into a document tree. DOM is convenient when code needs random access, element lookup, tree edits, or serialization after updates.

Imports
import klyn.io
import klyn.io.xml.dom
import org.w3c.dom
Parse XML Text

DOMParser reads XML from a string, file path, FilePath, or InputSource. The result is a DomDocument whose documentElement is the root element.

import klyn.io.xml.dom
import org.w3c.dom

xml = """
<catalog>
  <book id="klyn">
    <title>Klyn Guide</title>
  </book>
</catalog>
"""

parser = DOMParser()
document as DomDocument = parser.parseFromString(xml)
root as DomElement = document.documentElement

books = root.getElementsByTagName("book")
first = books[0] as DomElement
print(first.getAttribute("id"))
print(first.textContent.trim())
Parse Files

Use parseFromFile when the XML source lives on disk. Invalid XML raises DOMException; filesystem errors raise IOException.

import klyn.io
import klyn.io.xml.dom

parser = DOMParser()
document = parser.parseFromFile(FilePath("catalog.xml"))
print(document.documentElement.tagName)
Build and Serialize

DOM can also create a document programmatically. Append elements and text nodes, then use XMLSerializer to produce XML text.

import klyn.io.xml.dom

document = DomDocument()
root = document.createElement("catalog")
document.appendChild(root)

book = document.createElement("book")
book.setAttribute("id", "klyn")
root.appendChild(book)

book.appendChild(document.createTextNode("Klyn Guide"))
print(XMLSerializer.serialize(document, prettyPrint=true, indent=2))
DOM vs SAX

DOM is easier to query and mutate, but it keeps the document tree in memory. For large files where you only need a streaming pass, prefer SAX. For configuration files, generated documents, and tree transformations, DOM is usually the simpler model.