Standard library · Encoding and data

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. 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

func main 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

func main 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

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)
end
Output
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://example.com/</loc>
    <lastmod>2026-10-01</lastmod>
  </url>
  <url>
    <loc>https://example.com/search?q=tea&amp;page=2</loc>
    <lastmod>2026-10-12</lastmod>
  </url>
</urlset>

Text is escaped on the way out, so the & in the second URL is written as &amp;, 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

func main 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 := 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"))
end
Output
app: shop
listen: 0.0.0.0:8080
plugin auth enabled: true
plugin cache enabled: false
plugin search enabled: true
has a cache element: false

Guide: 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.

encoding-xml-guide-tokens.salam
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 &amp; 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++
            current = tok.attrs.Get("sku")
            if tok.attrs.Get("stock") == "0": outOfStock++ 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"
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 &amp; 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.

encoding-xml-guide-errors.salam
import encoding.xml

func check(label: str, text: str):
    try:
        mut d := xml.Parse(text)
        println label, "ok"
        xml.Free(d)
    catch e:
        println label, "line " + e.line + ", column " + e.column + ":", e.message
    end
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>")
    println "quick check:", xml.WellFormed("<x/>"), xml.WellFormed("<x>")
    println "escaped text:", xml.EscapeText("salt & pepper")
end
Output
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 &amp; 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

JobUse
Small config or response, read onceDecode, Child, Children, Attr
Find values anywhere in a documentParse and Select, SelectString, SelectNumber
Elements in namespacesXPath with local-name() and namespace-uri(), or LocalName and NamespaceURI
Walk or change a documentRoot, Elements, ChildAt, SetText, RemoveChild
Write a new documentNewDocument, CreateElement, Append, WriteIndent
Large files, one pass, no treeNewXMLTokenizer and NextToken
Check against a DTDthe DTD functions in the reference below
Convert to JSON or YAMLencoding.serde

Types

ElementDecl

#
struct ElementDecl

The declaration of one element in the DTD.

NameTypeDescription
namestr = ""The element name.
contentint = 1The content kind; one of the Content constants.
modelstr = ""The content model as text, such as (to, body).
rootint = -1The root of the model tree.
mixedVector<str>The names of the elements allowed in mixed content.
encoding-xml-DTD.salam
import encoding.xml

func main throw:
    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 good := try xml.Parse("<note id=\"n1\"><to>me</to><body>hello</body></note>")
    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 := try xml.Parse("<note><body>no recipient</body></note>")
    mut r2 := xml.Validate(bad, dtd)
    println r2.ok, r2.items.Len()
    println xml.ReportText(r2)
    xml.FreeReport(r2)
    mut inner := try xml.Parse("<!DOCTYPE a [<!ELEMENT a EMPTY>]><a>text</a>")
    mut r3 := xml.ValidateInternalSubset(inner)
    println r3.ok, inner.doctype
    xml.FreeReport(r3)
    mut ns := try xml.Parse("<a xmlns:x=\"urn:x\"><x:b/></a>")
    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)
end
Output
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

AttrDecl

#
struct AttrDecl

The declaration of one attribute in the DTD.

NameTypeDescription
elementstr = ""The element that owns the attribute.
namestr = ""The attribute name.
kindint = 0The attribute type; one of the Attr constants.
modeint = 1The default mode; one of the Default constants.
valuestr = ""The default value.
valuesVector<str>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

A document type definition.

NameTypeDescription
okbool = trueWhether the DTD was read correctly.
messagestr = ""The error message.
elementsVector<ElementDecl>The element declarations.
attributesVector<AttrDecl>The attribute declarations.
notationsVector<str>The notations.
modelsVector<ModelNode>The trees of the content models.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

Violation

#
struct Violation

One violation found during validation.

NameTypeDescription
messagestr = ""What the problem is.
lineint = 0The line.
colint = 0The column.
nodeint = -1The id of the node.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

Report

#
struct Report

The result of a validation.

NameTypeDescription
okbool = trueTrue when there is no violation at all.
itemsVector<Violation>The violations.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

XPathValue

#
struct XPathValue

The result of an XPath evaluation: a node set, a string, a number or a boolean.

NameTypeDescription
kindint = 0The kind of the result; one of the Value constants.
nodesNodeListThe nodes, when the result is a node set.
textstr = ""The string result.
numberf64 = 0The numeric result.
flagbool = falseThe boolean result.
encoding-xml-XPath.salam
import encoding.xml

func main throw:
    mut d := try xml.Parse(
        "<shop><item price=\"120\">tea</item><item price=\"80\">sugar</item><item price=\"45\">bread</item></shop>"
    )
    r := xml.DocumentNode(d)
    mut cheap := try xml.Select(d, r, "//item[@price < 100]")
    println cheap.items.Len()
    each n in cheap.items:
        println xml.Text(d, n)
    end
    xml.FreeList(cheap)
    println try xml.SelectString(d, r, "/shop/item[1]"),
        try xml.SelectNumber(d, r, "sum(//item/@price)"),
        try xml.SelectBoolean(d, r, "count(//item) = 3")
    last := try xml.SelectFirst(d, r, "//item[last()]")
    println xml.NodeName(d, last), xml.StringValue(d, last)
    mut v := try xml.Evaluate(d, r, "//item/@price")
    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 := try xml.Evaluate(d, r, "string-length('hello')")
    println num.kind == xml.ValueNumber, num.number, xml.ValueString, xml.ValueBoolean
    try:
        xml.Select(d, r, "//item[@")
    catch e:
        println e.KindName(), e.column, e.message
    end
    xml.Free(d)
end
Output
2
sugar
bread
tea 245 true
item bread
true 3
true 120 true
true 5 1 3
syntax error 9 a step was expected here

XPathVariables

#
struct XPathVariables

Named values that an XPath expression can read with $name.

NameTypeDescription
namesVector<str>The variable names, in the order they were added.
valuesVector<XPathValue>The value of each name, at the same position as its name.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

IndexOf

#
func IndexOf(name: str): int

The position of a name; -1 when it is not defined.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

Set

#
func Set(name: str, value: XPathValue)

Adds a variable, or replaces its value.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

SetString

#
func SetString(name: str, text: str)

SetNumber

#
func SetNumber(name: str, number: f64)

SetBoolean

#
func SetBoolean(name: str, flag: bool)

SetNodes

#
func SetNodes(name: str, nodes: NodeList)

Free

#
func Free()

Frees the variables and the node lists they hold.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

ParseOptions

#
struct ParseOptions

The parse options.

NameTypeDescription
preserve_whitespacebool = falseKeep text nodes that are only whitespace.
keep_commentsbool = trueKeep the comments.
keep_instructionsbool = trueKeep the processing instructions.
namespacesbool = trueResolve the namespaces.
expand_entitiesbool = trueReplace entities with their values.
max_depthint = 1024The greatest element depth.
max_entity_depthintThe greatest depth of nested entities.
max_entity_expansionintThe greatest text length after entities are expanded; a guard against the "entity bomb" attack.
encoding-xml-Parse.salam
import encoding.xml

func main throw:
    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 d := try xml.Parse(src)
    println xml.WellFormed(src), 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)
    try:
        mut bad := xml.Parse("<a><b></a>")
        xml.Free(bad)
    catch e:
        println e.line, e.column, e.code, e.ToStr()
    end
    println xml.WellFormed("<x/>"), xml.WellFormed("<x>")
    xml.Free(d)
    mut o := xml.DefaultOptions()
    o.keep_comments = false
    mut d2 := try xml.ParseWith(
        "<!DOCTYPE p [<!ENTITY site \"hello\">]><p xmlns:x=\"urn:x\" x:id=\"7\">&site; <b>b</b> end</p>",
        o
    )
    p := xml.Root(d2)
    println 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)
end
Output
true 1.0 true
library true true
2
b:book book b urn:books
4 3 2 /library[1]/b:book[1]
2 true 1
lang en
Dune Dune1965 true
2 year
year -1
9 2 3 3
false Dune
1 7 xml.mismatched_tag xml: </a> closes <b> (line 1, column 7)
true false
1 hello
[hello  end] 7
32 262144 1024

WriteOptions

#
struct WriteOptions

The write options.

NameTypeDescription
indentstr = ""The indent unit; empty means no indenting.
newlinestr = " "The newline between elements when there is indenting.
declarationbool = falseWrite the <?xml ...?> declaration.
doctypebool = falseWrite the DOCTYPE.
empty_as_pairbool = falseWrite an empty element as <a></a>.
sort_attributesbool = falsePut the attributes in alphabetical order.
escape_newlines_in_attributesbool = falseWrite a newline in an attribute value as &#10;.
encoding-xml-Build.salam
import encoding.xml

func main throw:
    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 d2 := try xml.Parse("<r b=\"2\"   a=\"1\"><x/></r>")
    println xml.Canonical(d2), xml.CanonicalNode(d2, xml.ChildAt(d2, xml.Root(d2), 0))
    xml.Free(d2)
    xml.Free(d)
end
Output
<note id="7" draft="yes"><!--recipient--><to>Maryam &amp; Reza</to><body><![CDATA[<b>bold</b>]]></body></note><?app v=1?>
true true
<note id="7">
  <!--recipient-->
  <to>everyone</to>
</note>
<?app v=1?>

<to>everyone</to> <to>everyone</to>

<?xml version="1.0" encoding="UTF-8"?>
<note id="7"><!--recipient--><to>everyone</to></note><?app v=1?>
<?xml version="1.0" encoding="UTF-8"?>
<note id="7"><!--recipient--><to>everyone</to></note><?app v=1?>

<r a="1" b="2"><x></x></r> <x></x>

Attribute

#
struct Attribute

One element attribute.

NameTypeDescription
ownerint = -1The id of the element.
namestr = ""The full name.
prefixstr = ""The prefix.
localstr = ""The name without the prefix.
uristr = ""The namespace URI.
valuestr = ""The value, with entities resolved.
lineint = 0The line.
colint = 0The column.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Node

#
struct Node

One node: an element, text, a comment and so on.

NameTypeDescription
kindint = 0The node kind; one of the Kind constants.
namestr = ""The full name with its prefix.
prefixstr = ""The namespace prefix.
localstr = ""The name without the prefix.
uristr = ""The namespace URI.
valuestr = ""The text of text nodes, comments and the like.
parentint = -1The id of the parent; -1 for the document node.
childrenVector<int>The ids of the children.
attrsVector<int>The indices of the attributes.
lineint = 0The line number in the text.
colint = 0The column number in the text.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Document

#
struct Document

One XML document, parsed or built. Nodes are taken out of it by number, their id.

NameTypeDescription
nodesVector<Node>Every node; the id of a node is its index in this vector.
attributesVector<Attribute>Every attribute.
versionstr = ""The version in the <?xml ...?> declaration.
encodingstr = ""The encoding in the declaration.
standalonestr = ""The standalone value in the declaration.
doctypestr = ""The name of the root element in <!DOCTYPE>.
doctype_publicstr = ""The public identifier of the DOCTYPE.
doctype_systemstr = ""The system identifier of the DOCTYPE.
internal_subsetstr = ""The text of the internal subset of the DOCTYPE, between [ and ].
entity_namesVector<str>The names of the defined entities.
entity_valuesVector<str>The values of the entities.
ownedVector<str>The strings the document holds.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

NodeList

#
struct NodeList

A list of node ids.

NameTypeDescription
itemsVector<int>The ids.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

XMLNode

#
struct XMLNode

A simple node: one element with its attributes, children and text; for small jobs without a document.

NameTypeDescription
tagstr = ""The element name.
attrsHashMap<str, str>The attributes.
childrenVector<XMLNode>The child elements.
textstr = ""The text of the element.
encoding-xml-Simple.salam
import encoding.xml
import encoding.value

func main throw:
    n := try 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>")
    try:
        xml.Decode("<a>")
    catch e:
        println e.code, e.line, e.column
    end
    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("&lt;p&gt; &amp; &#115;")
    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
end
Output
config true prod
true 5432 false
2 chat
<item id="3"><name>book</name></item>
<item id="3">
  <name>book</name>
</item>

<?xml version="1.0" encoding="UTF-8"?>
<item id="3"><name>book</name></item>
true false
xml.unclosed_tag 1 1
object{@env: string(prod), db: object{@host: string(localhost), @port: string(5432)}, feature: array[string(search), string(chat)]}
<root env="prod"><db host="localhost" port="5432"/><feature>search</feature><feature>chat</feature></root>
a &lt; b &amp; c &quot;x&quot; <p> & s
1 a 
3  hello
4  c
2 a 
1 2 3 4 5

XMLNodeList

#
struct XMLNodeList

A list of simple nodes.

NameTypeDescription
itemsVector<XMLNode>The nodes.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

XMLToken

#
struct XMLToken

One token from the tokenizer.

NameTypeDescription
kindint = 0The token kind; one of the XMLTok constants.
tagstr = ""The element name.
attrsHashMap<str, str>The attributes of a start element.
textstr = ""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

The tokenizer: reads the text token by token without building a tree; for large files.

NameTypeDescription
textstr = ""The input text.
posint = 0The current position.
badbool = falseReserved for errors; the tokenizer does not set it yet.
pendingEndstr = ""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

Constants and variables

DTD element content kinds

Content…#

Empty (EMPTY), any (ANY), mixed text and elements, or child elements only with a given model.

NameValue
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…#

The declared type of an attribute: text, id, id reference, entity, name token, a list of values, or a notation.

NameValue
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 (#REQUIRED), optional (#IMPLIED), fixed (#FIXED), or carrying a default value.

NameValue
DefaultRequired
0
DefaultImplied
1
DefaultFixed
2
DefaultValue
3

The example for this item is shown with the ones above: encoding-xml-DTD.salam

XPath result kinds

Value…#

The value of the kind field in the result of Evaluate.

NameValue
ValueNodeSet
0
ValueString
1
ValueNumber
2
ValueBoolean
3

The example for this item is shown with the ones above: encoding-xml-XPath.salam

Entity limits

Entity…#

The default values of max_entity_depth and max_entity_expansion in the parse options.

NameValue
EntityDepthLimit
32
EntityExpansionLimit
262144

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Node kinds

Kind…#

The kind of every node in the document.

NameValue
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"

The namespace URI of the 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/"

The namespace URI of xmlns.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Token kinds

XMLTok…#

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.

NameValue
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

Functions

ParseDTD

#
func ParseDTD(text: str): DTD

Reads DTD text.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

FreeDTD

#
func FreeDTD(dtd &: DTD)

Frees the memory of the DTD.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

FreeReport

#
func FreeReport(r &: Report)

Frees the memory of the report.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

ReportText

#
func ReportText(r: Report): str

Every violation, one per line.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

DeclaredElementCount

#
func DeclaredElementCount(dtd: DTD): int

The number of declared elements.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

DeclaredAttributeCount

#
func DeclaredAttributeCount(dtd: DTD): int

The number of declared attributes.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

Validate

#
func Validate(d: Document, dtd: DTD): Report

Validates the document against the given DTD: the content model, the required attributes, the allowed values and the ids.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

ValidateInternalSubset

#
func ValidateInternalSubset(d: Document): Report

Validates the document against the DTD inside its own DOCTYPE.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

CheckNamespaces

#
func CheckNamespaces(d: Document): Report

Checks that every prefix is defined.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

ApplyDefaults

#
func ApplyDefaults(d &: Document, dtd: DTD): int

Adds the default value of the attributes that were left out and returns how many.

The example for this item is shown with the ones above: encoding-xml-DTD.salam

Evaluate

#
func Evaluate(d: Document, context: int, expression: str): Throws<XPathValue>

Evaluates an XPath 1.0 expression from the context node. A bad expression throws an Error whose column points into the expression.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

EvaluateWith

#
func EvaluateWith(d: Document, context: int, expression: str, variables: XPathVariables): Throws<XPathValue>

Evaluates an XPath expression with $name variables. Throws NotFound with code xpath.unknown_variable when a name is not defined.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

FreeValue

#
func FreeValue(v &: XPathValue)

Frees the memory of the result.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

Select

#
func Select(d: Document, context: int, expression: str): Throws<NodeList>

The nodes the expression picks, such as //item[@price < 100]. Throws on a bad expression, and with TypeMismatch when the result is not a node set.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

SelectFirst

#
func SelectFirst(d: Document, context: int, expression: str): Throws<int>

The first node picked; -1 when there is none.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

SelectString

#
func SelectString(d: Document, context: int, expression: str): Throws<str>

Turns the result into a string.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

SelectNumber

#
func SelectNumber(d: Document, context: int, expression: str): Throws<f64>

Turns the result into a number, such as sum(//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): Throws<bool>

Turns the result into a boolean.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

SelectWith

#
func SelectWith(d: Document, context: int, expression: str, variables: XPathVariables): Throws<NodeList>

Like Select, with variable values.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

SelectFirstWith

#
func SelectFirstWith(d: Document, context: int, expression: str, variables: XPathVariables): Throws<int>

Like SelectFirst, with variable values.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

SelectStringWith

#
func SelectStringWith(d: Document, context: int, expression: str, variables: XPathVariables): Throws<str>

Like SelectString, with variable values.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

SelectNumberWith

#
func SelectNumberWith(d: Document, context: int, expression: str, variables: XPathVariables): Throws<f64>

Like SelectNumber, with variable values.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

SelectBooleanWith

#
func SelectBooleanWith(d: Document, context: int, expression: str, variables: XPathVariables): Throws<bool>

Like SelectBoolean, with variable values.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

IsAttributeRef

#
func IsAttributeRef(id: int): bool

True when an id returned by XPath points at an attribute.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

AttributeRef

#
func AttributeRef(aid: int): int

Turns an attribute index into the id that XPath returns for attributes.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

ReferencedAttribute

#
func ReferencedAttribute(d: Document, id: int): Attribute

The attribute that an XPath id points at.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

StringValue

#
func StringValue(d: Document, id: int): str

The string value of a node as XPath defines it: the text of every descendant, or the value of an attribute.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

NodeName

#
func NodeName(d: Document, id: int): str

The name of the node or attribute for an XPath id.

The example for this item is shown with the ones above: encoding-xml-XPath.salam

DefaultOptions

#
func DefaultOptions(): ParseOptions

The default parse options.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

ParseWith

#
func ParseWith(text: str, opts: ParseOptions): Throws<Document>

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.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Parse

#
func Parse(text: str): Throws<Document>

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 example for this item is shown with the ones above: encoding-xml-Parse.salam

WellFormed

#
func WellFormed(text: str): bool

True when the text is well formed.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

DefaultWriteOptions

#
func DefaultWriteOptions(): WriteOptions

The default write options.

The example for this item is shown with the ones above: encoding-xml-Build.salam

Write

#
func Write(d: Document): str

Writes the document compactly and without a declaration.

The example for this item is shown with the ones above: encoding-xml-Build.salam

WriteIndent

#
func WriteIndent(d: Document, unit: str): str

Writes the document with indenting.

The example for this item is shown with the ones above: encoding-xml-Build.salam

WriteWith

#
func WriteWith(d: Document, opts: WriteOptions): str

Writes the document with the given options.

The example for this item is shown with the ones above: encoding-xml-Build.salam

WriteNode

#
func WriteNode(d: Document, id: int): str

Writes one node and its descendants.

The example for this item is shown with the ones above: encoding-xml-Build.salam

WriteNodeIndent

#
func WriteNodeIndent(d: Document, id: int, unit: str): str

Writes one node with indenting.

The example for this item is shown with the ones above: encoding-xml-Build.salam

WriteDocument

#
func WriteDocument(d: Document): str

Writes the document together with the XML declaration.

The example for this item is shown with the ones above: encoding-xml-Build.salam

Canonical

#
func Canonical(d: Document): str

The canonical form of the document (Canonical XML): attributes sorted, empty elements as a pair, no extra whitespace; for comparing or for digital signatures.

The example for this item is shown with the ones above: encoding-xml-Build.salam

CanonicalNode

#
func CanonicalNode(d: Document, id: int): str

The canonical form of one node.

The example for this item is shown with the ones above: encoding-xml-Build.salam

NewDocument

#
func NewDocument(): Document

An empty document, to build one from scratch.

The example for this item is shown with the ones above: encoding-xml-Build.salam

Free

#
func Free(d &: Document)

Frees the memory of the document.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

FreeList

#
func FreeList(list &: NodeList)

Frees the memory of the list.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

NodeCount

#
func NodeCount(d: Document): int

The number of nodes.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

DocumentNode

#
func DocumentNode(d: Document): int

The id of the document node, whose child is the root element.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Root

#
func Root(d: Document): int

The id of the root element.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Exists

#
func Exists(d: Document, id: int): bool

True when the id points at a node.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Kind

#
func Kind(d: Document, id: int): int

The kind of the node.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Name

#
func Name(d: Document, id: int): str

The full name of the node.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

LocalName

#
func LocalName(d: Document, id: int): str

The name without the prefix.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Prefix

#
func Prefix(d: Document, id: int): str

The namespace prefix.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

NamespaceURI

#
func NamespaceURI(d: Document, id: int): str

The namespace URI of the node.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Value

#
func Value(d: Document, id: int): str

The text of a text or comment node; empty for an element.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Parent

#
func Parent(d: Document, id: int): int

The id of the parent.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Line

#
func Line(d: Document, id: int): int

The line number of the node in the text.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Column

#
func Column(d: Document, id: int): int

The column number of the node.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

IsElement

#
func IsElement(d: Document, id: int): bool

True when the node is an element.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

ChildCount

#
func ChildCount(d: Document, id: int): int

The number of children.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

ChildAt

#
func ChildAt(d: Document, id: int, index: int): int

The id of child number index.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

ChildNodes

#
func ChildNodes(d: Document, id: int): NodeList

Every child, text nodes included.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Elements

#
func Elements(d: Document, id: int): NodeList

The children that are elements.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

ElementsNamed

#
func ElementsNamed(d: Document, id: int, name: str): NodeList

The element children with the given name.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

FirstElementNamed

#
func FirstElementNamed(d: Document, id: int, name: str): int

The first child with the given name; -1 when there is none.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Descendants

#
func Descendants(d: Document, id: int): NodeList

Every descendant, in document order.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Ancestors

#
func Ancestors(d: Document, id: int): NodeList

The parent, its parent, and so on up to the document node.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

NextSibling

#
func NextSibling(d: Document, id: int): int

The next node with the same parent; -1 when there is none.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

PreviousSibling

#
func PreviousSibling(d: Document, id: int): int

The previous node with the same parent; -1 when there is none.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Depth

#
func Depth(d: Document, id: int): int

The depth of the node; the root element is 1.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

AttributeCount

#
func AttributeCount(d: Document, id: int): int

The number of attributes of the element.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

AttributeAt

#
func AttributeAt(d: Document, id: int, index: int): Attribute

Attribute number index.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

HasAttribute

#
func HasAttribute(d: Document, id: int, name: str): bool

True when the element has this attribute.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

AttributeValue

#
func AttributeValue(d: Document, id: int, name: str): str

The value of the attribute with the full name; an empty string when there is none.

The 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): str

The value of the attribute with the given namespace URI and local name.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Text

#
func Text(d: Document, id: int): str

All the text inside the element and its descendants, one after another.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

DirectText

#
func DirectText(d: Document, id: int): str

Only the text of the direct children, without the text of inner elements.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

Path

#
func Path(d: Document, id: int): str

The path of the node, such as /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): int

The number of entities defined in the DOCTYPE.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

EntityValue

#
func EntityValue(d: Document, name: str): str

The value of one entity.

The example for this item is shown with the ones above: encoding-xml-Parse.salam

CreateElement

#
func CreateElement(d &: Document, name: str): int

Makes a new element and returns its id; it is not attached anywhere yet.

The example for this item is shown with the ones above: encoding-xml-Build.salam

CreateText

#
func CreateText(d &: Document, text: str): int

Makes a new text node and returns its id; it is not attached anywhere yet.

The example for this item is shown with the ones above: encoding-xml-Build.salam

CreateCData

#
func CreateCData(d &: Document, text: str): int

Makes a new CDATA section and returns its id; it is not attached anywhere yet.

The example for this item is shown with the ones above: encoding-xml-Build.salam

CreateComment

#
func CreateComment(d &: Document, text: str): int

Makes a new comment and returns its id; it is not attached anywhere yet.

The example for this item is shown with the ones above: encoding-xml-Build.salam

CreateProcessingInstruction

#
func CreateProcessingInstruction(d &: Document, target: str, data: str): int

Makes a new processing instruction and returns its id; it is not attached anywhere yet.

The example for this item is shown with the ones above: encoding-xml-Build.salam

Append

#
func Append(d &: Document, parent: int, child: int)

Makes the node the last child of the parent.

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)

Puts the node before the child 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): bool

Detaches the child and says whether it was found.

The 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)

Sets or adds an attribute.

The example for this item is shown with the ones above: encoding-xml-Build.salam

RemoveAttribute

#
func RemoveAttribute(d &: Document, id: int, name: str): bool

Removes an attribute.

The example for this item is shown with the ones above: encoding-xml-Build.salam

SetText

#
func SetText(d &: Document, id: int, text: str)

Replaces every child of the element with one text node.

The example for this item is shown with the ones above: encoding-xml-Build.salam

UnescapeEntities

#
func UnescapeEntities(s: str): str

Resolves entities and character references such as &lt; and &#1587;.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

EscapeText

#
func EscapeText(s: str): str

Escapes the special characters for text.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

EscapeAttr

#
func EscapeAttr(s: str): str

Escapes the special characters for an attribute value, the quote included.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

NewXMLTokenizer

#
func NewXMLTokenizer(text: str): XMLTokenizer

A new tokenizer over the text.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

NextToken

#
func NextToken(tz &: XMLTokenizer): XMLToken

The next token; XMLTokEOF 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): XMLNode

A new simple node with the given name.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

Found

#
func Found(n: XMLNode): bool

True when the node was found, meaning its name is not empty.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

HasAttr

#
func HasAttr(node: XMLNode, name: str): bool

True when the simple node has this attribute.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

Attr

#
func Attr(node: XMLNode, name: str): str

The value of an attribute of a simple node.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

SetAttr

#
func SetAttr(node &: XMLNode, name: str, value: str)

Sets an attribute of a simple node.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

AppendChild

#
func AppendChild(node &: XMLNode, child: XMLNode)

Adds a child to a simple node.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

Child

#
func Child(node: XMLNode, tag: str): XMLNode

The first child with the given name; when there is none, a node whose Found is false.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

Children

#
func Children(node: XMLNode, tag: str): XMLNodeList

Every child with the given name.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

Decode

#
func Decode(text: str): Throws<XMLNode>

Turns the text into a simple node. When the text is not well-formed XML it throws an Error with the line and column.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

Valid

#
func Valid(text: str): bool

True when the text is valid XML.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

Encode

#
func Encode(node: XMLNode): str

Turns a simple node into text.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

EncodeIndent

#
func EncodeIndent(node: XMLNode, unit: str): str

Writes a simple node with indenting.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

EncodeDeclaration

#
func EncodeDeclaration(node: XMLNode): str

Writes a simple node together with the XML declaration.

The example for this item is shown with the ones above: encoding-xml-Simple.salam

ToValue

#
func ToValue(node: XMLNode): value.Value

Turns a simple node into a value; the attributes get an @ 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): XMLNode

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.

The example for this item is shown with the ones above: encoding-xml-Simple.salam