encoding/xml
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.
Parsereads the text into aDocument, and every node has a numeric id you pass to functions such asName,AttributeValue,ElementsandText. 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 plainXMLNodestructs. 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.
What trips people up
- XPath matches names as written. A name test compares the element's full name, prefix included, with the query.
//entryfinds Atom entries in a default namespace, and//m:thumbnailworks only if the document uses the prefixm. When the prefix may vary, testlocal-name()andnamespace-uri(); the namespaces guide shows how. - Every value is text.
TextandSelectStringreturn strings; useSelectNumberor convert yourself. - Whitespace-only text is dropped by default. Set
preserve_whitespaceinParseOptionswhen indentation matters, for example in mixed content. - Free what you take. A
Documentand eachNodeListfromSelecthold memory untilFreeandFreeList. - 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
WellFormedfirst 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.
import encoding.xml
func main:
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 err := xml.NoError()
mut d := xml.Parse(feed, err)
if not err.ok:
println "bad feed:", xml.ErrorText(err)
ret 1
end
top := xml.DocumentNode(d)
println "feed:", xml.SelectString(d, top, "/rss/channel/title", err)
println "posts:", xml.SelectNumber(d, top, "count(//item)", err)
mut items := xml.Select(d, top, "//item[category = 'tutorial']", err)
each it in items.items:
println "-", xml.SelectString(d, it, "title", err), "<" + xml.SelectString(d, it, "link", err) + ">"
end
xml.FreeList(items)
xml.Free(d)
endThe 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.
import encoding.xml
func main:
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 err := xml.NoError()
mut d := xml.Parse(feed, err)
if not err.ok:
println xml.ErrorText(err)
ret 1
end
top := xml.DocumentNode(d)
println "entries by name: ", xml.SelectNumber(d, top, "count(//entry)", err)
println "with prefix m: ", xml.SelectNumber(d, top, "count(//m:thumbnail)", err)
println "with prefix media:", xml.SelectNumber(d, top, "count(//media:thumbnail)", err)
query := "//*[local-name() = 'thumbnail' and namespace-uri() = 'http://search.yahoo.com/mrss/']"
mut thumbs := xml.Select(d, top, query, err)
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//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.
import encoding.xml
func add_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))
end
func main:
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)
endText 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: DecodeStrict gives the root as a plain struct, 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.
import encoding.xml
func main:
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>`
mut ok := false
app := xml.DecodeStrict(text, ok)
if not ok:
println "config is not well-formed"
ret 1
end
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 := true
if xml.HasAttr(p, "enabled"):
enabled = xml.Attr(p, "enabled") == "true"
end
println "plugin", xml.Attr(p, "name"), "enabled:", enabled
end
println "has a cache element:", xml.Found(xml.Child(app, "cache"))
endGuide: scan a product feed with the tokenizer
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.
import encoding.xml
import str
func main:
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 := false
mut products := 0
mut outOfStock := 0
mut done := false
until not done:
tok := xml.NextToken(tz)
if tok.kind == xml.XMLTokEOF:
done = true
else tok.kind == xml.XMLTokStartElement and tok.tag == "product":
products += 1
current = tok.attrs.get("sku")
if tok.attrs.get("stock") == "0": outOfStock += 1 end
else tok.kind == xml.XMLTokStartElement and tok.tag == "name":
inName = true
else tok.kind == xml.XMLTokEndElement and tok.tag == "name":
inName = false
else tok.kind == xml.XMLTokText and inName:
println current, "is", str.Trim(tok.text)
end
end
println products, "products,", outOfStock, "out of stock"
endAttributes 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 stops at the first problem and ErrorText gives a line, a column and a readable reason, ready to show to whoever wrote the file. WellFormed only answers yes or no.
import encoding.xml
func check(label: str, text: str):
mut err := xml.NoError()
mut d := xml.Parse(text, err)
if err.ok:
println label, "ok"
else:
println label, xml.ErrorText(err)
end
xml.Free(d)
end
func main:
check("good: ", "<a><b>1</b></a>")
check("mismatch: ", "<a>\n <b>1</a>")
check("two roots: ", "<a/><b/>")
check("bad entity:", "<a>&nope;</a>")
check("raw amp: ", "<a>salt & pepper</a>")
mut err := xml.NoError()
println "quick check:", xml.WellFormed("<x/>", err), xml.WellFormed("<x>", err)
println "escaped text:", xml.EscapeText("salt & pepper")
endThe 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 |
| Walk or change a document | Root, Elements, ChildAt, SetText, RemoveChild |
| Write a new document | NewDocument, CreateElement, Append, WriteIndent |
| Large files, one pass, no tree | NewXMLTokenizer and NextToken |
| Check against a DTD | the DTD functions in the reference below |
| Convert to JSON or YAML | encoding/serde |
Types
WriteOptions
struct WriteOptions| Name | Type | Description |
|---|---|---|
indent | str = "" | The indent unit; empty means no indenting. |
newline | str = "
" | The newline between elements when there is indenting. |
declaration | bool = false | Write the <?xml ...?> declaration. |
doctype | bool = false | Write the DOCTYPE. |
empty_as_pair | bool = false | Write an empty element as <a></a>. |
sort_attributes | bool = false | Put the attributes in alphabetical order. |
escape_newlines_in_attributes | bool = false | Write a newline in an attribute value as . |
import encoding.xml
func main:
mut d := xml.NewDocument()
root := xml.CreateElement(d, "note")
xml.Append(d, xml.DocumentNode(d), root)
xml.SetAttribute(d, root, "id", "7")
xml.SetAttribute(d, root, "draft", "yes")
recipient := xml.CreateElement(d, "to")
xml.Append(d, root, recipient)
xml.Append(d, recipient, xml.CreateText(d, "Maryam & Reza"))
body := xml.CreateElement(d, "body")
xml.Append(d, root, body)
xml.Append(d, body, xml.CreateCData(d, "<b>bold</b>"))
xml.InsertBefore(d, root, xml.CreateComment(d, "recipient"), recipient)
xml.Append(d, xml.DocumentNode(d), xml.CreateProcessingInstruction(d, "app", "v=1"))
println xml.Write(d)
println xml.RemoveAttribute(d, root, "draft"), xml.RemoveChild(d, root, body)
xml.SetText(d, recipient, "everyone")
println xml.WriteIndent(d, " ")
println xml.WriteNode(d, recipient), xml.WriteNodeIndent(d, recipient, "\t")
mut o := xml.DefaultWriteOptions()
o.declaration = true
o.empty_as_pair = true
println xml.WriteWith(d, o)
println xml.WriteDocument(d)
mut err := xml.NoError()
mut d2 := xml.Parse("<r b=\"2\" a=\"1\"><x/></r>", err)
println xml.Canonical(d2), xml.CanonicalNode(d2, xml.ChildAt(d2, xml.Root(d2), 0))
xml.Free(d2)
xml.Free(d)
endParseError
struct ParseError| Name | Type | Description |
|---|---|---|
ok | bool = true | Whether the parse succeeded. |
message | str = "" | The error message. |
line | int = 0 | The line of the error. |
col | int = 0 | The column of the error. |
offset | int = 0 | The position of the error in bytes. |
import encoding.xml
func main:
src := "<?xml version=\"1.0\"?>\n<library xmlns:b=\"urn:books\">\n <!-- the list -->\n <b:book id=\"1\" lang=\"en\"><title>Dune</title><year>1965</year></b:book>\n <b:book id=\"2\"><title>Solaris</title></b:book>\n</library>"
mut err := xml.NoError()
mut d := xml.Parse(src, err)
println err.ok, d.version, xml.NodeCount(d) > 0
r := xml.Root(d)
println xml.Name(d, r), xml.Kind(d, r) == xml.KindElement, xml.Parent(d, r) == xml.DocumentNode(d)
mut books := xml.Elements(d, r)
println books.items.len()
b := books.items[0]
println xml.Name(d, b), xml.LocalName(d, b), xml.Prefix(d, b), xml.NamespaceURI(d, b)
println xml.Line(d, b), xml.Column(d, b), xml.Depth(d, b), xml.Path(d, b)
println xml.AttributeCount(d, b), xml.HasAttribute(d, b, "lang"), xml.AttributeValue(d, b, "id")
a := xml.AttributeAt(d, b, 1)
println a.name, a.value
t := xml.FirstElementNamed(d, b, "title")
println xml.Text(d, t), xml.Text(d, b), xml.IsElement(d, t)
println xml.ChildCount(d, b), xml.Name(d, xml.ChildAt(d, b, 1))
println xml.Name(d, xml.NextSibling(d, t)), xml.PreviousSibling(d, t)
mut all := xml.Descendants(d, r)
mut named := xml.ElementsNamed(d, r, "b:book")
mut up := xml.Ancestors(d, t)
mut kids := xml.ChildNodes(d, r)
println all.items.len(), named.items.len(), up.items.len(), kids.items.len()
println xml.Exists(d, 9999), xml.Value(d, xml.ChildAt(d, t, 0))
xml.FreeList(all)
xml.FreeList(named)
xml.FreeList(up)
xml.FreeList(kids)
xml.FreeList(books)
_ := xml.Parse("<a><b></a>", err)
println err.ok, err.line, xml.ErrorText(err)
println xml.WellFormed("<x/>", err)
xml.Free(d)
mut o := xml.DefaultOptions()
o.keep_comments = false
mut d2 := xml.ParseWith("<!DOCTYPE p [<!ENTITY site \"hello\">]><p xmlns:x=\"urn:x\" x:id=\"7\">&site; <b>b</b> end</p>", o, err)
p := xml.Root(d2)
println err.ok, xml.EntityCount(d2), xml.EntityValue(d2, "site")
println "[" + xml.DirectText(d2, p) + "]", xml.AttributeValueNS(d2, p, "urn:x", "id")
println xml.EntityDepthLimit, xml.EntityExpansionLimit, o.max_depth
xml.Free(d2)
endParseOptions
struct ParseOptions| Name | Type | Description |
|---|---|---|
preserve_whitespace | bool = false | Keep text nodes that are only whitespace. |
keep_comments | bool = true | Keep the comments. |
keep_instructions | bool = true | Keep the processing instructions. |
namespaces | bool = true | Resolve the namespaces. |
expand_entities | bool = true | Replace entities with their values. |
max_depth | int = 1024 | The greatest element depth. |
max_entity_depth | int | The greatest depth of nested entities. |
max_entity_expansion | int | The greatest text length after entities are expanded; a guard against the "entity bomb" attack. |
The example for this item is shown with the ones above: encoding-xml-Parse.salam
ElementDecl
struct ElementDecl| Name | Type | Description |
|---|---|---|
name | str = "" | The element name. |
content | int = 1 | The content kind; one of the Content constants. |
model | str = "" | The content model as text, such as (to, body). |
root | int = -1 | The root of the model tree. |
mixed | Vector | The names of the elements allowed in mixed content. |
import encoding.xml
func main:
dtd := xml.ParseDTD("<!ELEMENT note (to, body)>\n<!ELEMENT to (#PCDATA)>\n<!ELEMENT body (#PCDATA)>\n<!ATTLIST note id ID #REQUIRED kind (a|b) \"a\">")
println dtd.ok, xml.DeclaredElementCount(dtd), xml.DeclaredAttributeCount(dtd)
el := dtd.elements[0]
println el.name, el.content == xml.ContentChildren, el.model
at := dtd.attributes[1]
println at.name, at.kind == xml.AttrEnumeration, at.mode == xml.DefaultValue, at.value, at.values
mut err := xml.NoError()
mut good := xml.Parse("<note id=\"n1\"><to>me</to><body>hello</body></note>", err)
mut report := xml.Validate(good, dtd)
println report.ok
xml.FreeReport(report)
println xml.ApplyDefaults(good, dtd), xml.AttributeValue(good, xml.Root(good), "kind")
mut bad := xml.Parse("<note><body>no recipient</body></note>", err)
mut r2 := xml.Validate(bad, dtd)
println r2.ok, r2.items.len()
println xml.ReportText(r2)
xml.FreeReport(r2)
mut inner := xml.Parse("<!DOCTYPE a [<!ELEMENT a EMPTY>]><a>text</a>", err)
mut r3 := xml.ValidateInternalSubset(inner)
println r3.ok, inner.doctype
xml.FreeReport(r3)
mut ns := xml.Parse("<a xmlns:x=\"urn:x\"><x:b/></a>", err)
mut r4 := xml.CheckNamespaces(ns)
println r4.ok
xml.FreeReport(r4)
mut dtd2 := dtd
xml.FreeDTD(dtd2)
xml.Free(good)
xml.Free(bad)
xml.Free(inner)
xml.Free(ns)
endAttrDecl
struct AttrDecl| Name | Type | Description |
|---|---|---|
element | str = "" | The element that owns the attribute. |
name | str = "" | The attribute name. |
kind | int = 0 | The attribute type; one of the Attr constants. |
mode | int = 1 | The default mode; one of the Default constants. |
value | str = "" | The default value. |
values | Vector | The allowed values of an enumerated attribute. |
The example for this item is shown with the ones above: encoding-xml-DTD.salam
DTD
struct DTD| Name | Type | Description |
|---|---|---|
ok | bool = true | Whether the DTD was read correctly. |
message | str = "" | The error message. |
elements | Vector | The element declarations. |
attributes | Vector | The attribute declarations. |
notations | Vector | The notations. |
models | Vector | The trees of the content models. |
The example for this item is shown with the ones above: encoding-xml-DTD.salam
Violation
struct Violation| Name | Type | Description |
|---|---|---|
message | str = "" | What the problem is. |
line | int = 0 | The line. |
col | int = 0 | The column. |
node | int = -1 | The id of the node. |
The example for this item is shown with the ones above: encoding-xml-DTD.salam
Report
struct Report| Name | Type | Description |
|---|---|---|
ok | bool = true | True when there is no violation at all. |
items | Vector | The violations. |
The example for this item is shown with the ones above: encoding-xml-DTD.salam
XMLNode
struct XMLNode| Name | Type | Description |
|---|---|---|
tag | str = "" | The element name. |
attrs | HashMap | The attributes. |
children | Vector | The child elements. |
text | str = "" | The text of the element. |
import encoding.xml
import encoding.value
func main:
n := xml.Decode("<config env=\"prod\"><db host=\"localhost\" port=\"5432\"/><feature>search</feature><feature>chat</feature></config>")
println n.tag, xml.HasAttr(n, "env"), xml.Attr(n, "env")
db := xml.Child(n, "db")
println xml.Found(db), xml.Attr(db, "port"), xml.Found(xml.Child(n, "cache"))
feats := xml.Children(n, "feature")
println feats.items.len(), feats.items[1].text
mut item := xml.NewXMLNode("item")
xml.SetAttr(item, "id", "3")
mut name := xml.NewXMLNode("name")
name.text = "book"
xml.AppendChild(item, name)
println xml.Encode(item)
println xml.EncodeIndent(item, " ")
println xml.EncodeDeclaration(item)
println xml.Valid("<a><b/></a>"), xml.Valid("<a><b></a>")
mut ok := false
_ := xml.DecodeStrict("<a>", ok)
println ok
v := xml.ToValue(n)
println value.ToDebugString(v)
println xml.Encode(xml.FromValue(v, "root"))
println xml.EscapeText("a < b & c"), xml.EscapeAttr(`"x"`), xml.UnescapeEntities("<p> & s")
mut tz := xml.NewXMLTokenizer("<a x=\"1\">hello<!--c--></a>")
until true:
t := xml.NextToken(tz)
if t.kind == xml.XMLTokEOF or t.kind == xml.XMLTokError:
break
end
println t.kind, t.tag, t.text
end
println xml.XMLTokStartElement, xml.XMLTokEndElement, xml.XMLTokText, xml.XMLTokComment, xml.XMLTokCData
endXMLNodeList
struct XMLNodeList| Name | Type | Description |
|---|---|---|
items | Vector | The nodes. |
The example for this item is shown with the ones above: encoding-xml-Simple.salam
XMLToken
struct XMLToken| Name | Type | Description |
|---|---|---|
kind | int = 0 | The token kind; one of the XMLTok constants. |
tag | str = "" | The element name. |
attrs | HashMap | The attributes of a start element. |
text | str = "" | The text of a text or comment token. |
The example for this item is shown with the ones above: encoding-xml-Simple.salam
XMLTokenizer
struct XMLTokenizer| Name | Type | Description |
|---|---|---|
text | str = "" | The input text. |
pos | int = 0 | The current position. |
bad | bool = false | Reserved for errors; the tokenizer does not set it yet. |
pendingEnd | str = "" | A self closing element whose end token has not been handed out yet. |
The example for this item is shown with the ones above: encoding-xml-Simple.salam
XPathValue
struct XPathValue| Name | Type | Description |
|---|---|---|
kind | int = 0 | The kind of the result; one of the Value constants. |
nodes | NodeList | The nodes, when the result is a node set. |
text | str = "" | The string result. |
number | f64 = 0 | The numeric result. |
flag | bool = false | The boolean result. |
import encoding.xml
func main:
mut err := xml.NoError()
mut d := xml.Parse("<shop><item price=\"120\">tea</item><item price=\"80\">sugar</item><item price=\"45\">bread</item></shop>", err)
r := xml.DocumentNode(d)
mut cheap := xml.Select(d, r, "//item[@price < 100]", err)
println cheap.items.len()
each n in cheap.items:
println xml.Text(d, n)
end
xml.FreeList(cheap)
println xml.SelectString(d, r, "/shop/item[1]", err), xml.SelectNumber(d, r, "sum(//item/@price)", err), xml.SelectBoolean(d, r, "count(//item) = 3", err)
last := xml.SelectFirst(d, r, "//item[last()]", err)
println xml.NodeName(d, last), xml.StringValue(d, last)
mut v := xml.Evaluate(d, r, "//item/@price", err)
println v.kind == xml.ValueNodeSet, v.nodes.items.len()
first := v.nodes.items[0]
println xml.IsAttributeRef(first), xml.ReferencedAttribute(d, first).value, xml.IsAttributeRef(xml.AttributeRef(0))
xml.FreeValue(v)
num := xml.Evaluate(d, r, "string-length('hello')", err)
println num.kind == xml.ValueNumber, num.number, xml.ValueString, xml.ValueBoolean
_ := xml.Select(d, r, "//item[@", err)
println err.ok
xml.Free(d)
endAttribute
struct Attribute| Name | Type | Description |
|---|---|---|
owner | int = -1 | The id of the element. |
name | str = "" | The full name. |
prefix | str = "" | The prefix. |
local | str = "" | The name without the prefix. |
uri | str = "" | The namespace URI. |
value | str = "" | The value, with entities resolved. |
line | int = 0 | The line. |
col | int = 0 | The column. |
The example for this item is shown with the ones above: encoding-xml-Parse.salam
Node
struct Node| Name | Type | Description |
|---|---|---|
kind | int = 0 | The node kind; one of the Kind constants. |
name | str = "" | The full name with its prefix. |
prefix | str = "" | The namespace prefix. |
local | str = "" | The name without the prefix. |
uri | str = "" | The namespace URI. |
value | str = "" | The text of text nodes, comments and the like. |
parent | int = -1 | The id of the parent; -1 for the document node. |
children | Vector | The ids of the children. |
attrs | Vector | The indices of the attributes. |
line | int = 0 | The line number in the text. |
col | int = 0 | The column number in the text. |
The example for this item is shown with the ones above: encoding-xml-Parse.salam
Document
struct Document| Name | Type | Description |
|---|---|---|
nodes | Vector | Every node; the id of a node is its index in this vector. |
attributes | Vector | Every attribute. |
version | str = "" | The version in the <?xml ...?> declaration. |
encoding | str = "" | The encoding in the declaration. |
standalone | str = "" | The standalone value in the declaration. |
doctype | str = "" | The name of the root element in <!DOCTYPE>. |
doctype_public | str = "" | The public identifier of the DOCTYPE. |
doctype_system | str = "" | The system identifier of the DOCTYPE. |
internal_subset | str = "" | The text of the internal subset of the DOCTYPE, between [ and ]. |
entity_names | Vector | The names of the defined entities. |
entity_values | Vector | The values of the entities. |
owned | Vector | The strings the document holds. |
The example for this item is shown with the ones above: encoding-xml-Parse.salam
NodeList
struct NodeList| Name | Type | Description |
|---|---|---|
items | Vector | The ids. |
The example for this item is shown with the ones above: encoding-xml-Parse.salam
Constants and variables
Entity limits Entity…
max_entity_depth and max_entity_expansion in the parse options.| Name | Value |
|---|---|
EntityDepthLimit | 32 |
EntityExpansionLimit | 262144 |
The example for this item is shown with the ones above: encoding-xml-Parse.salam
DTD element content kinds Content…
EMPTY), any (ANY), mixed text and elements, or child elements only with a given model.| Name | Value |
|---|---|
ContentEmpty | 0 |
ContentAny | 1 |
ContentMixed | 2 |
ContentChildren | 3 |
The example for this item is shown with the ones above: encoding-xml-DTD.salam
DTD attribute types Attr…
| Name | Value |
|---|---|
AttrCData | 0 |
AttrId | 1 |
AttrIdRef | 2 |
AttrIdRefs | 3 |
AttrEntity | 4 |
AttrEntities | 5 |
AttrNmToken | 6 |
AttrNmTokens | 7 |
AttrEnumeration | 8 |
AttrNotation | 9 |
The example for this item is shown with the ones above: encoding-xml-DTD.salam
DTD attribute default modes Default…
#REQUIRED), optional (#IMPLIED), fixed (#FIXED), or carrying a default value.| Name | Value |
|---|---|
DefaultRequired | 0 |
DefaultImplied | 1 |
DefaultFixed | 2 |
DefaultValue | 3 |
The example for this item is shown with the ones above: encoding-xml-DTD.salam
Token kinds XMLTok…
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.| Name | Value |
|---|---|
XMLTokStartElement | 1 |
XMLTokEndElement | 2 |
XMLTokText | 3 |
XMLTokComment | 4 |
XMLTokCData | 5 |
XMLTokEOF | 6 |
XMLTokError | 7 |
The example for this item is shown with the ones above: encoding-xml-Simple.salam
XPath result kinds Value…
kind field in the result of Evaluate.| Name | Value |
|---|---|
ValueNodeSet | 0 |
ValueString | 1 |
ValueNumber | 2 |
ValueBoolean | 3 |
The example for this item is shown with the ones above: encoding-xml-XPath.salam
Node kinds Kind…
kind of every node in the document.| Name | Value |
|---|---|
KindDocument | 0 |
KindElement | 1 |
KindText | 2 |
KindCData | 3 |
KindComment | 4 |
KindProcessingInstruction | 5 |
KindDoctype | 6 |
The example for this item is shown with the ones above: encoding-xml-Parse.salam
XMLNamespaceURI
const XMLNamespaceURI: str = "http://www.w3.org/XML/1998/namespace"xml prefix.The example for this item is shown with the ones above: encoding-xml-Parse.salam
XMLNSNamespaceURI
const XMLNSNamespaceURI: str = "http://www.w3.org/2000/xmlns/"xmlns.The example for this item is shown with the ones above: encoding-xml-Parse.salam
Functions
DefaultWriteOptions
func DefaultWriteOptions(): WriteOptionsThe example for this item is shown with the ones above: encoding-xml-Build.salam
Write
func Write(d: Document): strThe example for this item is shown with the ones above: encoding-xml-Build.salam
WriteIndent
func WriteIndent(d: Document, unit: str): strThe example for this item is shown with the ones above: encoding-xml-Build.salam
WriteWith
func WriteWith(d: Document, opts: WriteOptions): strThe example for this item is shown with the ones above: encoding-xml-Build.salam
WriteNode
func WriteNode(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-Build.salam
WriteNodeIndent
func WriteNodeIndent(d: Document, id: int, unit: str): strThe example for this item is shown with the ones above: encoding-xml-Build.salam
WriteDocument
func WriteDocument(d: Document): strThe example for this item is shown with the ones above: encoding-xml-Build.salam
Canonical
func Canonical(d: Document): strThe example for this item is shown with the ones above: encoding-xml-Build.salam
CanonicalNode
func CanonicalNode(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-Build.salam
DefaultOptions
func DefaultOptions(): ParseOptionsThe example for this item is shown with the ones above: encoding-xml-Parse.salam
NoError
func NoError(): ParseErrorThe example for this item is shown with the ones above: encoding-xml-Parse.salam
ErrorText
func ErrorText(e: ParseError): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
ParseWith
func ParseWith(text: str, opts: ParseOptions, err &: ParseError): DocumentThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Parse
func Parse(text: str, err &: ParseError): Documenterr.ok becomes false when the XML is not well formed.The example for this item is shown with the ones above: encoding-xml-Parse.salam
WellFormed
func WellFormed(text: str, err &: ParseError): boolThe example for this item is shown with the ones above: encoding-xml-Parse.salam
ParseDTD
func ParseDTD(text: str): DTDThe example for this item is shown with the ones above: encoding-xml-DTD.salam
FreeDTD
func FreeDTD(dtd &: DTD)The example for this item is shown with the ones above: encoding-xml-DTD.salam
FreeReport
func FreeReport(r &: Report)The example for this item is shown with the ones above: encoding-xml-DTD.salam
ReportText
func ReportText(r: Report): strThe example for this item is shown with the ones above: encoding-xml-DTD.salam
DeclaredElementCount
func DeclaredElementCount(dtd: DTD): intThe example for this item is shown with the ones above: encoding-xml-DTD.salam
DeclaredAttributeCount
func DeclaredAttributeCount(dtd: DTD): intThe example for this item is shown with the ones above: encoding-xml-DTD.salam
Validate
func Validate(d: Document, dtd: DTD): ReportThe example for this item is shown with the ones above: encoding-xml-DTD.salam
ValidateInternalSubset
func ValidateInternalSubset(d: Document): ReportThe example for this item is shown with the ones above: encoding-xml-DTD.salam
CheckNamespaces
func CheckNamespaces(d: Document): ReportThe example for this item is shown with the ones above: encoding-xml-DTD.salam
ApplyDefaults
func ApplyDefaults(d &: Document, dtd: DTD): intThe example for this item is shown with the ones above: encoding-xml-DTD.salam
UnescapeEntities
func UnescapeEntities(s: str): str< and س.The example for this item is shown with the ones above: encoding-xml-Simple.salam
EscapeText
func EscapeText(s: str): strThe example for this item is shown with the ones above: encoding-xml-Simple.salam
EscapeAttr
func EscapeAttr(s: str): strThe example for this item is shown with the ones above: encoding-xml-Simple.salam
NewXMLTokenizer
func NewXMLTokenizer(text: str): XMLTokenizerThe example for this item is shown with the ones above: encoding-xml-Simple.salam
NextToken
func NextToken(tz &: XMLTokenizer): XMLTokenXMLTokEOF when the text is used up. Comments, CDATA and text come as their own kinds; <?...?> and <!DOCTYPE> are skipped.The example for this item is shown with the ones above: encoding-xml-Simple.salam
NewXMLNode
func NewXMLNode(tag: str): XMLNodeThe example for this item is shown with the ones above: encoding-xml-Simple.salam
Found
func Found(n: XMLNode): boolThe example for this item is shown with the ones above: encoding-xml-Simple.salam
HasAttr
func HasAttr(node: XMLNode, name: str): boolThe example for this item is shown with the ones above: encoding-xml-Simple.salam
Attr
func Attr(node: XMLNode, name: str): strThe example for this item is shown with the ones above: encoding-xml-Simple.salam
SetAttr
func SetAttr(node &: XMLNode, name: str, value: str)The example for this item is shown with the ones above: encoding-xml-Simple.salam
AppendChild
func AppendChild(node &: XMLNode, child: XMLNode)The example for this item is shown with the ones above: encoding-xml-Simple.salam
Child
func Child(node: XMLNode, tag: str): XMLNodeFound is false.The example for this item is shown with the ones above: encoding-xml-Simple.salam
Children
func Children(node: XMLNode, tag: str): XMLNodeListThe example for this item is shown with the ones above: encoding-xml-Simple.salam
DecodeStrict
func DecodeStrict(text: str, ok &: bool): XMLNodeok becomes false when it is not valid.The example for this item is shown with the ones above: encoding-xml-Simple.salam
Decode
func Decode(text: str): XMLNodeThe example for this item is shown with the ones above: encoding-xml-Simple.salam
Valid
func Valid(text: str): boolThe example for this item is shown with the ones above: encoding-xml-Simple.salam
Encode
func Encode(node: XMLNode): strThe example for this item is shown with the ones above: encoding-xml-Simple.salam
EncodeIndent
func EncodeIndent(node: XMLNode, unit: str): strThe example for this item is shown with the ones above: encoding-xml-Simple.salam
EncodeDeclaration
func EncodeDeclaration(node: XMLNode): strThe example for this item is shown with the ones above: encoding-xml-Simple.salam
ToValue
func ToValue(node: XMLNode): value.Value@ prefix and children sharing a name become an array.The example for this item is shown with the ones above: encoding-xml-Simple.salam
FromValue
func FromValue(v: value.Value, rootTag: str): XMLNodeThe example for this item is shown with the ones above: encoding-xml-Simple.salam
Evaluate
func Evaluate(d: Document, context: int, expression: str, err &: ParseError): XPathValuecontext node.The example for this item is shown with the ones above: encoding-xml-XPath.salam
FreeValue
func FreeValue(v &: XPathValue)The example for this item is shown with the ones above: encoding-xml-XPath.salam
Select
func Select(d: Document, context: int, expression: str, err &: ParseError): NodeList//item[@price < 100].The example for this item is shown with the ones above: encoding-xml-XPath.salam
SelectFirst
func SelectFirst(d: Document, context: int, expression: str, err &: ParseError): intThe example for this item is shown with the ones above: encoding-xml-XPath.salam
SelectString
func SelectString(d: Document, context: int, expression: str, err &: ParseError): strThe example for this item is shown with the ones above: encoding-xml-XPath.salam
SelectNumber
func SelectNumber(d: Document, context: int, expression: str, err &: ParseError): f64sum(//item/@price).The example for this item is shown with the ones above: encoding-xml-XPath.salam
SelectBoolean
func SelectBoolean(d: Document, context: int, expression: str, err &: ParseError): boolThe example for this item is shown with the ones above: encoding-xml-XPath.salam
IsAttributeRef
func IsAttributeRef(id: int): boolThe example for this item is shown with the ones above: encoding-xml-XPath.salam
AttributeRef
func AttributeRef(aid: int): intThe example for this item is shown with the ones above: encoding-xml-XPath.salam
ReferencedAttribute
func ReferencedAttribute(d: Document, id: int): AttributeThe example for this item is shown with the ones above: encoding-xml-XPath.salam
StringValue
func StringValue(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-XPath.salam
NodeName
func NodeName(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-XPath.salam
NewDocument
func NewDocument(): DocumentThe example for this item is shown with the ones above: encoding-xml-Build.salam
Free
func Free(d &: Document)The example for this item is shown with the ones above: encoding-xml-Parse.salam
FreeList
func FreeList(list &: NodeList)The example for this item is shown with the ones above: encoding-xml-Parse.salam
NodeCount
func NodeCount(d: Document): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
DocumentNode
func DocumentNode(d: Document): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Root
func Root(d: Document): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Exists
func Exists(d: Document, id: int): boolThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Kind
func Kind(d: Document, id: int): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Name
func Name(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
LocalName
func LocalName(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Prefix
func Prefix(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
NamespaceURI
func NamespaceURI(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Value
func Value(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Parent
func Parent(d: Document, id: int): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Line
func Line(d: Document, id: int): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Column
func Column(d: Document, id: int): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
IsElement
func IsElement(d: Document, id: int): boolThe example for this item is shown with the ones above: encoding-xml-Parse.salam
ChildCount
func ChildCount(d: Document, id: int): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
ChildAt
func ChildAt(d: Document, id: int, index: int): intindex.The example for this item is shown with the ones above: encoding-xml-Parse.salam
ChildNodes
func ChildNodes(d: Document, id: int): NodeListThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Elements
func Elements(d: Document, id: int): NodeListThe example for this item is shown with the ones above: encoding-xml-Parse.salam
ElementsNamed
func ElementsNamed(d: Document, id: int, name: str): NodeListThe example for this item is shown with the ones above: encoding-xml-Parse.salam
FirstElementNamed
func FirstElementNamed(d: Document, id: int, name: str): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Descendants
func Descendants(d: Document, id: int): NodeListThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Ancestors
func Ancestors(d: Document, id: int): NodeListThe example for this item is shown with the ones above: encoding-xml-Parse.salam
NextSibling
func NextSibling(d: Document, id: int): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
PreviousSibling
func PreviousSibling(d: Document, id: int): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Depth
func Depth(d: Document, id: int): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
AttributeCount
func AttributeCount(d: Document, id: int): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
AttributeAt
func AttributeAt(d: Document, id: int, index: int): Attributeindex.The example for this item is shown with the ones above: encoding-xml-Parse.salam
HasAttribute
func HasAttribute(d: Document, id: int, name: str): boolThe example for this item is shown with the ones above: encoding-xml-Parse.salam
AttributeValue
func AttributeValue(d: Document, id: int, name: str): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
AttributeValueNS
func AttributeValueNS(d: Document, id: int, uri: str, local: str): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Text
func Text(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
DirectText
func DirectText(d: Document, id: int): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
Path
func Path(d: Document, id: int): str/library[1]/b:book[1].The example for this item is shown with the ones above: encoding-xml-Parse.salam
EntityCount
func EntityCount(d: Document): intThe example for this item is shown with the ones above: encoding-xml-Parse.salam
EntityValue
func EntityValue(d: Document, name: str): strThe example for this item is shown with the ones above: encoding-xml-Parse.salam
CreateElement
func CreateElement(d &: Document, name: str): intThe example for this item is shown with the ones above: encoding-xml-Build.salam
CreateText
func CreateText(d &: Document, text: str): intThe example for this item is shown with the ones above: encoding-xml-Build.salam
CreateCData
func CreateCData(d &: Document, text: str): intThe example for this item is shown with the ones above: encoding-xml-Build.salam
CreateComment
func CreateComment(d &: Document, text: str): intThe example for this item is shown with the ones above: encoding-xml-Build.salam
CreateProcessingInstruction
func CreateProcessingInstruction(d &: Document, target: str, data: str): intThe example for this item is shown with the ones above: encoding-xml-Build.salam
Append
func Append(d &: Document, parent: int, child: int)The example for this item is shown with the ones above: encoding-xml-Build.salam
InsertBefore
func InsertBefore(d &: Document, parent: int, child: int, before: int)before.The example for this item is shown with the ones above: encoding-xml-Build.salam
RemoveChild
func RemoveChild(d &: Document, parent: int, child: int): boolThe example for this item is shown with the ones above: encoding-xml-Build.salam
SetAttribute
func SetAttribute(d &: Document, id: int, name: str, value: str)The example for this item is shown with the ones above: encoding-xml-Build.salam
RemoveAttribute
func RemoveAttribute(d &: Document, id: int, name: str): boolThe example for this item is shown with the ones above: encoding-xml-Build.salam
SetText
func SetText(d &: Document, id: int, text: str)The example for this item is shown with the ones above: encoding-xml-Build.salam