Reading, building and writing XML, with XPath, DTD validation, namespaces and a light simple interface.
import encoding.xml
This package reads, queries, edits and writes XML: feeds, sitemaps, SVG, SOAP replies, office files and old configuration formats. It has three interfaces for three sizes of job.
•
The document interface is the complete one. Parse reads the text into a Document, and every node has a numeric id you pass to functions such as Name, AttributeValue, Elements and Text. XPath 1.0 queries, namespaces, entities, DTD validation, editing and canonical output all work on it.
•
The simple node interface (Decode, Child, Attr, Encode) keeps the tree in plain XMLNode structs. It suits a small config or API reply you read once, and it is what encoding.serde uses to convert XML to and from a Value.
•
The tokenizer (NewXMLTokenizer, NextToken) hands out start tags, end tags and text one at a time without building a tree.
If you control both ends and only need to move data, encoding.json is simpler. Reach for this package when the other side speaks XML.
Untrusted input
Parse is safe to run on documents from outside. External entities (<!ENTITY x SYSTEM "file:///etc/passwd">) are never fetched, so a reference to one fails as undeclared, and entity expansion is capped by max_entity_expansion (256 KB by default) and max_entity_depth (32), which stops the "billion laughs" attack. Element nesting is capped at 1024 levels.
Errors
Parse, ParseWith, the simple Decode, Evaluate and the Select functions are declared throw: on a broken document or a bad XPath expression they throw an Error and give back nothing half-built. Catch it with try: ... catch e:, or write try before the call in a function that is itself declared throw. e.message says what is wrong, e.line and e.column point at it (in the expression, for XPath), and e.kind sorts it: Syntax, UnexpectedEnd, NotFound for an undeclared entity, prefix or XPath function, AlreadyExists for an attribute given twice, OutOfRange for the entity and depth limits, InvalidUtf8, TypeMismatch and InvalidArgument. e.code names the common cases exactly, such as xml.unclosed_tag, xml.mismatched_tag or xpath.unknown_function. WellFormed and Valid answer the same question as a plain bool.
What trips people up
•
XPath matches names as written. A name test compares the element's full name, prefix included, with the query. //entry finds Atom entries in a default namespace, and //m:thumbnail works only if the document uses the prefix m. When the prefix may vary, test local-name() and namespace-uri(); the namespaces guide shows how.
•
Every value is text.Text and SelectString return strings; use SelectNumber or convert yourself.
•
Whitespace-only text is dropped by default. Set preserve_whitespace in ParseOptions when indentation matters, for example in mixed content.
•
Free what you take. A Document and each NodeList from Select hold memory until Free and FreeList.
•
The tokenizer does not check the document. It does not match end tags to start tags, it returns the whitespace between elements as text tokens, and it needs the whole text in memory. Run WellFormed first if the input may be broken.
Guide: read a feed with XPath
RSS and Atom feeds, sitemaps, SVG and office files are all XML, and XPath is the quickest way to pull values out of them. SelectString and SelectNumber answer a whole query in one call; Select returns the matching nodes, and a query run from one of those nodes is relative to it, so title means the title of that item.
encoding-xml-guide-rss.salam
import encoding.xml
funcmain throw:
feed := `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>Salam blog</title>
<item>
<title>Salam 0.5.5 is out</title>
<link>https://example.com/posts/055</link>
<category>release</category>
</item>
<item>
<title>Writing a JSON API</title>
<link>https://example.com/posts/json-api</link>
<category>tutorial</category>
</item>
<item>
<title>The Persian keywords</title>
<link>https://example.com/posts/persian</link>
<category>tutorial</category>
</item>
</channel>
</rss>`mut d := try xml.Parse(feed)
top := xml.DocumentNode(d)
println"feed:", try xml.SelectString(d, top, "/rss/channel/title")
println"posts:", try xml.SelectNumber(d, top, "count(//item)")
mut items := try xml.Select(d, top, "//item[category = 'tutorial']")
each it in items.items:
println"-",
try xml.SelectString(d, it, "title"),
"<" + try xml.SelectString(d, it, "link") + ">"end
xml.FreeList(items)
xml.Free(d)
end
Output
feed: Salam blog
posts: 3
- Writing a JSON API <https://example.com/posts/json-api>
- The Persian keywords <https://example.com/posts/persian>
The filter [category = 'tutorial'] keeps only the items whose child element has that text. Free the node list with FreeList and the document with Free when you are done.
Guide: namespaces in an Atom feed
Atom feeds, SVG, SOAP and office files put their elements in namespaces, often several at once. This feed uses Atom as the default namespace and Media RSS under the prefix m. The program shows how XPath in this package treats names, and the query that works whatever prefix the publisher chose.
encoding-xml-guide-namespaces.salam
import encoding.xml
funcmain throw:
feed := `<feed xmlns="http://www.w3.org/2005/Atom" xmlns:m="http://search.yahoo.com/mrss/">
<title>Salam videos</title>
<entry>
<title>Install Salam</title>
<m:thumbnail url="https://cdn.example/install.jpg"/>
</entry>
<entry>
<title>Your first web server</title>
<m:thumbnail url="https://cdn.example/server.jpg"/>
</entry>
</feed>`mut d := try xml.Parse(feed)
top := xml.DocumentNode(d)
println"entries by name: ", try xml.SelectNumber(d, top, "count(//entry)")
println"with prefix m: ", try xml.SelectNumber(d, top, "count(//m:thumbnail)")
println"with prefix media:", try xml.SelectNumber(d, top, "count(//media:thumbnail)")
query := "//*[local-name() = 'thumbnail' and namespace-uri() = 'http://search.yahoo.com/mrss/']"mut thumbs := try xml.Select(d, top, query)
each t in thumbs.items:
println xml.Name(d, t), "local:", xml.LocalName(d, t), "->", xml.AttributeValue(d, t, "url")
end
xml.FreeList(thumbs)
root := xml.Root(d)
println"root namespace:", xml.NamespaceURI(d, root)
xml.Free(d)
end
Output
entries by name: 2
with prefix m: 2
with prefix media: 0
m:thumbnail local: thumbnail -> https://cdn.example/install.jpg
m:thumbnail local: thumbnail -> https://cdn.example/server.jpg
root namespace: http://www.w3.org/2005/Atom
//entry matches because the entries have no prefix, and //m:thumbnail because the document happens to say m. A feed that writes media:thumbnail instead would break the second query, while the local-name() and namespace-uri() test keeps working. Outside XPath, LocalName, Prefix and NamespaceURI give the parts of any node's name, and AttributeValueNS reads a namespaced attribute.
Guide: generate a sitemap
To write XML, build a document node by node with CreateElement, CreateText and Append, then write it out. A small helper per repeated element keeps the code short. WriteWith with declaration and indent set produces a file ready to serve as sitemap.xml.
encoding-xml-guide-sitemap.salam
import encoding.xml
funcadd_url(d &: xml.Document, parent: int, loc: str, changed: str):
u := xml.CreateElement(d, "url")
xml.Append(d, parent, u)
l := xml.CreateElement(d, "loc")
xml.Append(d, u, l)
xml.Append(d, l, xml.CreateText(d, loc))
m := xml.CreateElement(d, "lastmod")
xml.Append(d, u, m)
xml.Append(d, m, xml.CreateText(d, changed))
endfuncmain:
mut d := xml.NewDocument()
root := xml.CreateElement(d, "urlset")
xml.Append(d, xml.DocumentNode(d), root)
xml.SetAttribute(d, root, "xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")
add_url(d, root, "https://example.com/", "2026-10-01")
add_url(d, root, "https://example.com/search?q=tea&page=2", "2026-10-12")
mut o := xml.DefaultWriteOptions()
o.declaration = true
o.indent = " "print xml.WriteWith(d, o)
xml.Free(d)
end
Text is escaped on the way out, so the & in the second URL is written as &, as XML requires. Building the document this way means you never have to escape anything by hand.
Guide: a small config with the simple nodes
For a short file you read once, the simple interface is enough: Decode gives the root as a plain struct, or throws when the file is not well formed, Child and Children find elements by name, and Attr reads an attribute. Found tells you whether Child found anything, and HasAttr lets an attribute have a default.
encoding-xml-guide-config.salam
import encoding.xml
funcmain throw:
text := `<app name="shop">
<listen host="0.0.0.0" port="8080"/>
<plugin name="auth" enabled="true"/>
<plugin name="cache" enabled="false"/>
<plugin name="search"/>
</app>`
app := try xml.Decode(text)
println"app:", xml.Attr(app, "name")
listen := xml.Child(app, "listen")
if xml.Found(listen):
println"listen:", xml.Attr(listen, "host") + ":" + xml.Attr(listen, "port")
end
plugins := xml.Children(app, "plugin")
each p in plugins.items:
mut enabled := trueif xml.HasAttr(p, "enabled"):
enabled = xml.Attr(p, "enabled") == "true"endprintln"plugin", xml.Attr(p, "name"), "enabled:", enabled
endprintln"has a cache element:", xml.Found(xml.Child(app, "cache"))
end
Price lists and catalogue exports can have hundreds of thousands of records, and you often need only a few fields. The tokenizer walks the text once and builds no tree, so memory stays at the size of the text. Keep a little state, here which product you are in and whether you are inside a <name>, and react to the tokens you care about.
encoding-xml-guide-tokens.salam
import encoding.xml
importstrfuncmain:
feed := `<products>
<product sku="TEA-01" stock="14"><name>Green tea</name><price>4.50</price></product>
<product sku="CUP-02" stock="0"><name>Glass cup</name><price>7.25</price></product>
<product sku="POT-03" stock="3"><name>Tea pot & lid</name><price>21.00</price></product>
</products>`mut tz := xml.NewXMLTokenizer(feed)
mut current := ""mut inName := falsemut products := 0mut outOfStock := 0mut done := falseuntilnot done:
tok := xml.NextToken(tz)
if tok.kind == xml.XMLTokEOF:
done = trueelse tok.kind == xml.XMLTokStartElement and tok.tag == "product":
products++
current = tok.attrs.Get("sku")
if tok.attrs.Get("stock") == "0": outOfStock++ endelse tok.kind == xml.XMLTokStartElement and tok.tag == "name":
inName = trueelse tok.kind == xml.XMLTokEndElement and tok.tag == "name":
inName = falseelse tok.kind == xml.XMLTokText and inName:
println current, "is", str.Trim(tok.text)
endendprintln products, "products,", outOfStock, "out of stock"end
Output
TEA-01 is Green tea
CUP-02 is Glass cup
POT-03 is Tea pot & lid
3 products, 1 out of stock
Attributes of a start tag arrive in tok.attrs, and text has its entities decoded, so & comes out as &. Text tokens include the whitespace between tags, which is why the program trims the name and ignores text outside <name>. A self-closing tag such as <br/> gives a start token followed by an end token.
Guide: report broken XML
XML is strict: one root, every tag closed in order, every & part of an entity. Parse throws at the first problem, and the error carries a line, a column and a readable reason in e.message, ready to show to whoever wrote the file. WellFormed only answers yes or no.
good: ok
mismatch: line 2, column 7: </a> closes <b>
two roots: line 1, column 5: a document may hold only one root element, and <b> is a second
bad entity: line 1, column 4: the entity "&nope;" is not declared
raw amp: line 1, column 9: an entity reference has no closing semicolon
quick check: true false
escaped text: salt & pepper
The last case is the most common one in hand-written files: a bare & in text. When you build XML from strings yourself, pass text through EscapeText and attribute values through EscapeAttr, or build the document with the functions above, which escape for you.
Which interface for which job
Job
Use
Small config or response, read once
Decode, Child, Children, Attr
Find values anywhere in a document
Parse and Select, SelectString, SelectNumber
Elements in namespaces
XPath with local-name() and namespace-uri(), or LocalName and NamespaceURI
true 3 2
note true (to, body)
kind true true a ["a", "b"]
true
1 a
false 2
line 1, column 1: the children of <note> do not match (to, body)
line 1, column 1: <note> is missing the required attribute "id"
false a
true
The kind of every token from the tokenizer. A self-closing tag gives a start token and then an end token; XMLTokError is reserved and not returned yet.
Reads the text with the given options. When the XML is not well formed it throws an Error with the line, the column and a code such as xml.unclosed_tag.
Reads the text with the default options. When the XML is not well formed it throws an Error with the line, the column and a code such as xml.mismatched_tag.
The canonical form of the document (Canonical XML): attributes sorted, empty elements as a pair, no extra whitespace; for comparing or for digital signatures.
Turns a value into a simple node with the given root name, by the same rule. Numbers and booleans are written as their text; null becomes an empty element.