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 has two interfaces. The document interface is the complete one: Parse reads the text into a document, and every node has a numeric id you use to get its name, attributes, children and text. XPath, DTD validation, namespaces, entities and the canonical form all work on that document.

The simple node interface (Decode, Child, Attr) is for small jobs, such as reading a small configuration file, and keeps the tree directly in plain structs. The XMLTokenizer reads the text without building a tree at all.

Types

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

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.
mixedVectorThe names of the elements allowed in mixed content.
encoding-xml-DTD.salam
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)
end
Outputtrue 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.
valuesVectorThe 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.
elementsVectorThe element declarations.
attributesVectorThe attribute declarations.
notationsVectorThe notations.
modelsVectorThe 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.
itemsVectorThe violations.

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

ParseError

struct ParseError
An XML parse error.
NameTypeDescription
okbool = trueWhether the parse succeeded.
messagestr = ""The error message.
lineint = 0The line of the error.
colint = 0The column of the error.
offsetint = 0The position of the error in bytes.
encoding-xml-Parse.salam
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)
end
Outputtrue 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 false 1 line 1, column 7: </a> closes <b> true true 1 hello [hello end] 7 32 262144 1024

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.

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.
attrsHashMapThe attributes.
childrenVectorThe child elements.
textstr = ""The text of the element.
encoding-xml-Simple.salam
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("&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
Outputconfig 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 false object{feature: array[string(search), string(chat)], @env: string(prod), db: object{@port: string(5432), @host: string(localhost)}} <root env="prod"><feature>search</feature><feature>chat</feature><db host="localhost" port="5432"/></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
itemsVectorThe 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.
attrsHashMapThe 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 = falseAn error happened.
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

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:
    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)
end
Output2 sugar bread tea 245 true item bread true 3 true 120 true true 5 1 3 false

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.
childrenVectorThe ids of the children.
attrsVectorThe 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
nodesVectorEvery node; the id of a node is its index in this vector.
attributesVectorEvery 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_namesVectorThe names of the defined entities.
entity_valuesVectorThe values of the entities.
ownedVectorThe 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
itemsVectorThe ids.

The example for this item is shown with the ones above: encoding-xml-Parse.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
ContentEmpty0
ContentAny1
ContentMixed2
ContentChildren3

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
AttrCData0
AttrId1
AttrIdRef2
AttrIdRefs3
AttrEntity4
AttrEntities5
AttrNmToken6
AttrNmTokens7
AttrEnumeration8
AttrNotation9

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
DefaultRequired0
DefaultImplied1
DefaultFixed2
DefaultValue3

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

Entity limits Entity…

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

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.
NameValue
XMLTokStartElement1
XMLTokEndElement2
XMLTokText3
XMLTokComment4
XMLTokCData5
XMLTokEOF6
XMLTokError7

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

XPath result kinds Value…

The value of the kind field in the result of Evaluate.
NameValue
ValueNodeSet0
ValueString1
ValueNumber2
ValueBoolean3

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

Node kinds Kind…

The kind of every node in the document.
NameValue
KindDocument0
KindElement1
KindText2
KindCData3
KindComment4
KindProcessingInstruction5
KindDoctype6

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

Functions

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

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

DefaultOptions

func DefaultOptions(): ParseOptions
The default parse options.

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

NoError

func NoError(): ParseError
An empty error to pass to the parse functions.

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

ErrorText

func ErrorText(e: ParseError): str
Writes the error as "line, column: message".

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

ParseWith

func ParseWith(text: str, opts: ParseOptions, err &: ParseError): Document
Reads the text with the given options.

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

Parse

func Parse(text: str, err &: ParseError): Document
Reads the text; err.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): bool
True when the text is well formed.

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

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

DecodeStrict

func DecodeStrict(text: str, ok &: bool): XMLNode
Turns the text into a simple node; ok 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): XMLNode
Turns the text into a simple node.

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.

The 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): XPathValue
Evaluates an XPath 1.0 expression from the context node.

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, err &: ParseError): NodeList
The nodes the expression picks, such as //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): 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, err &: ParseError): 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, err &: ParseError): 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, err &: ParseError): bool
Turns the result into a boolean.

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

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