xml

XML parsing, generation, and XPath queries using libxml2

Files

FileDescription
.editorconfigEditor formatting configuration
.gitignoreGit ignore rules for build artifacts and dependencies
.tool-versionsasdf tool versions (Zig, Kit)
LICENSEMIT license file
README.mdThis file
c/kit_xml.cC FFI wrapper
c/kit_xml.hC header for FFI wrapper
examples/basic.kitParse XML and query with XPath expressions
examples/create.kitBuild XML documents programmatically
examples/xml.kitFull demo of parsing, XPath, building, and RSS-style data
examples/xpath-advanced.kitComplex XPath queries and filtering
kit.tomlPackage manifest with metadata and dependencies
src/xml.kitXML parsing, XPath queries, node navigation, and document creation
tests/xml.test.kitTests for constants, types, node variants, and public API behavior

Dependencies

No Kit package dependencies.

This package links against libxml2 and includes a small C wrapper for libxml2 APIs that are awkward to call directly through Kit FFI.

Install the native dependency before building or running examples:

# macOS
brew install libxml2

# Ubuntu/Debian
sudo apt install libxml2-dev

# Fedora
sudo dnf install libxml2-devel

Installation

kit add gitlab.com/kit-lang/packages/kit-xml.git

Usage

import Kit.XML as XML

main = fn =>
  xml = "<?xml version='1.0'?>
<library>
  <book id='1' category='fiction'>
    <title>The Great Gatsby</title>
    <author>F. Scott Fitzgerald</author>
  </book>
  <book id='2' category='non-fiction'>
    <title>A Brief History of Time</title>
    <author>Stephen Hawking</author>
  </book>
</library>"

  # Parse an XML string
  match XML.parse xml
    | Err err ->
      println "Failed to parse XML: ${Error.message err}"
    | Ok doc ->
      # Documents own their nodes and must be freed when no longer needed
      defer XML.free doc

      # Read values with XPath
      match XML.xpath-text doc "//book/title/text()"
        | Ok titles ->
          List.for-each (fn(title) => println "Title: ${title}") titles
        | Err err ->
          println "XPath error: ${Error.message err}"

      # Get a single XPath result
      match XML.xpath-first doc "//book[@id='2']/author/text()"
        | Ok author -> println "Book 2 author: ${author}"
        | Err err -> println "XPath error: ${Error.message err}"

      # Navigate nodes directly
      match XML.root doc
        | Ok root ->
          count = XML.xpath-count doc "//book"
          println "Root element: ${XML.name root}"
          println "Book count: ${Int.to-string count}"
        | Err err ->
          println "Root error: ${Error.message err}"

main

Create XML documents programmatically:

import Kit.XML as XML

main = fn =>
  match XML.build "config" [
    ("database", "localhost"), 
    ("port", "5432"), 
    ("username", "admin")
  ]
    | Ok doc ->
      defer XML.free doc
      println (XML.stringify-pretty doc)
    | Err err ->
      println "Error: ${Error.message err}"

main

Development

Running Examples

Run examples with the interpreter:

kit run --allow=ffi examples/basic.kit
kit run --allow=ffi examples/create.kit
kit run --allow=ffi examples/xpath-advanced.kit

Compile examples to native binaries:

kit build --allow=ffi examples/basic.kit && ./basic

Running Tests

Run the test suite:

kit test

Run the test suite with coverage:

kit test --coverage

Running kit dev

Run the standard development workflow:

kit dev

This will:

  1. Build the native C wrapper
  2. Format and check source files in src/ and examples
  3. Run tests in tests/ with coverage

Running Parity Checks

Verify interpreter, compiler, and built binary output behavior for examples:

kit parity --no-spinner --failures-only

Generating Documentation

Generate API documentation from doc comments:

kit doc

Note: Kit sources with doc comments (##) will generate HTML documents in docs/*.html.

Cleaning Build Artifacts

Remove generated files, caches, and build artifacts:

kit task clean

Note: Defined in kit.toml.

Local Installation

To install this package locally for development:

kit install

This installs the package to ~/.kit/packages/@kit/xml/, making it available for import as Kit.XML in other projects.

After changing kit.toml, src/xml.kit, or files in c/, reinstall the package before testing it from another Kit project.

Native Integration

The Kit API lives in src/xml.kit. Native helper functions live in c/kit_xml.c and are declared in c/kit_xml.h.

The native package configuration is in the [native] section of kit.toml. It compiles c/kit_xml.c, includes headers from c/, and links both the package wrapper library and xml2.

License

This package is released under the MIT License - see LICENSE for details.

libxml2 is also released under the MIT License.

Exported Functions & Types

XMLError

XML error type for typed error handling.

Variants

XMLParseError {message}
XMLXPathError {message}
XMLCreateError {message}

xml-parse-default

Default XML parsing options.

xml-parse-recover

Recover from parsing errors.

xml-parse-noent

Substitute entity references.

xml-parse-dtdload

Load external DTD.

xml-parse-dtdattr

Default DTD attributes.

xml-parse-dtdvalid

Validate with DTD.

xml-parse-noerror

Suppress error reports.

xml-parse-nowarning

Suppress warning reports.

xml-parse-noblanks

Remove blank nodes.

xml-element-node

XML element node type.

xml-attribute-node

XML attribute node type.

xml-text-node

XML text node type.

xml-cdata-node

XML CDATA section node type.

xml-comment-node

XML comment node type.

xml-document-node

XML document node type.

Node

Represents different types of XML nodes.

Variants

ElementNode {Element}
An XML element with structure
TextNode {String}
A text content node
CommentNode {String}
An XML comment

parse

Parses an XML string into a document.

String -> Result XmlDoc XMLError

parse-with-options

Parses an XML string with custom parsing options.

String -> Int -> Result XmlDoc XMLError

parse-file

Parses an XML file into a document.

NonEmptyString -> Result XmlDoc XMLError

free

Frees a document from memory.

XmlDoc -> Void

xpath

Executes an XPath query and returns matching nodes.

XmlDoc -> String -> Result XPathResult XMLError

xpath-ns

Executes an XPath query with namespace prefixes.

XmlDoc -> String -> List (String, String) -> Result XPathResult XMLError

xpath-text

Gets text content from XPath result nodes.

XmlDoc -> String -> Result (List String) XMLError

xpath-first

Gets the first text result from an XPath query.

XmlDoc -> String -> Result String XMLError

xpath-exists?

Checks if an XPath query matches any nodes.

XmlDoc -> String -> Bool

xpath-count

Counts the number of nodes matching an XPath query.

XmlDoc -> String -> Int

root

Gets the root element of a document.

XmlDoc -> Result XmlNode XMLError

name

Gets the name of a node.

XmlNode -> String

text

Gets the text content of a node.

XmlNode -> String

attr

Gets the value of a node attribute.

XmlNode -> NonEmptyString -> Option String

has-attr?

Checks if a node has a specific attribute.

XmlNode -> NonEmptyString -> Bool

node-type

Gets the type of a node.

XmlNode -> Int

is-element?

Checks if a node is an element node.

XmlNode -> Bool

is-text?

Checks if a node is a text node.

XmlNode -> Bool

children

Gets all child nodes of a node.

XmlNode -> List XmlNode

child-elements

Gets child element nodes only (skips text nodes).

XmlNode -> List XmlNode

find-child

Finds the first child element with a specific name.

XmlNode -> NonEmptyString -> Option XmlNode

find-children

Finds all child elements with a specific name.

XmlNode -> NonEmptyString -> List XmlNode

stringify

Converts a document to an XML string.

XmlDoc -> String

stringify-pretty

Converts a document to a formatted XML string.

XmlDoc -> String

doc

Creates an empty XML document.

() -> Result XmlDoc XMLError

element

Creates an element node with a specific tag name.

NonEmptyString -> Result XmlNode XMLError

set-root

Sets the root element of a document.

XmlDoc -> XmlNode -> Result () XMLError

add-child

Adds a child element to a parent node.

XmlNode -> NonEmptyString -> String -> Result XmlNode XMLError

set-attr

Sets an attribute on a node.

XmlNode -> NonEmptyString -> String -> Result () XMLError

set-text

Sets the text content of a node.

XmlNode -> String -> Result () XMLError

parse-root

Parses an XML string and returns document with root element.

String -> Result (XmlDoc, XmlNode) XMLError

build

Builds a simple XML document from a nested structure.

NonEmptyString -> List (String, String) -> Result XmlDoc XMLError