RAS Playground 日本語 GitHub

RAS standard library

XML (xml)

The RAS standard library module for reading and writing XML. It parses and writes in RAS without using MSXML, so running and testing without Excel gives the same results. A document is represented as a tree of XmlNode (elements, text, CDATA, comments). The functions are emitted into the VBA module RAS_Xml, and XmlNode into a class module.

import * as xml from "xml";

export function readOrders(p: string) {
    const root = xml.read(p);                                    // the root element; the encoding is decided by the BOM and the XML declaration
    for (const order of root.elements("order")) {               // child elements
        debug.print(order.attr("id"), order.childText("customer/name"), order.element("total").text);
    }
    debug.print(root.descendants("item").length);               // descendant elements

    const doc = xml.element("orders");                           // a new document
    const o = doc.addElement("order").setAttr("id", "A-1");
    o.addElement("name", "Apples & oranges");                    // & etc. become & when written
    o.addComment("memo");
    xml.write(p + ".out.xml", doc);                              // <?xml version="1.0" encoding="UTF-8"?> and indent 2
    debug.print(xml.stringify(doc, 0));                          // single line
}

Reference

Class xml.XmlNode

An XML node. type is one of "element", "text", "cdata" (a CDATA section) and "comment". Elements have name, attributes and children; the others hold their content in value. Create nodes with xml.parse / xml.element.

The methods that search by name (element / elements / descendants) match a name without a prefix (ns:) also against names with their prefix removed ("item" also matches <ns:item>).

#
type: string = "element"

"element", "text", "cdata" or "comment".

#
name: string = ""

The element's name (in the form ns:item when it has a prefix). "" for nodes that are not elements.

#
value: string = ""

The content of a text, CDATA or comment node (not used for elements).

#
attributes: Map<string, string> = new Map<string, string>()

The element's attributes (name → value, in the order written).

#
get children(): XmlNode[]

The element's child nodes (in the order written; the array is a copy, so changing it does not change the node. Add with addElement / append, remove with remove).

Example: for (const c of node.children) { if (c.isElement) … }

#
get childCount(): int

Number of child nodes.

#
attr(name: string, fallback: string = ""): string

The value of the attribute (fallback if absent; default "").

Example: item.attr("id")

#
hasAttr(name: string): boolean

Whether the attribute exists.

#
setAttr(name: string, value: string): XmlNode

Sets the attribute (adding it if absent). Returns this node (so calls can be chained).

Example: node.setAttr("id", "A-1").setAttr("count", ${n})

#
removeAttr(name: string): void

Removes the attribute (does nothing if absent).

#
get text(): string
set text(value: string)

All the text inside (the text and CDATA of the descendants joined; for text, CDATA and comment nodes, their value). Assigning to it replaces the children with that one text (for elements).

Example: const price = cDbl(item.element("price").text);

#
get isElement(): boolean

Whether the node is an element.

#
elements(path: string = "*"): XmlNode[]

The child elements (with path, those with that name). path can name deeper levels joined with / ("order/item"). "*" matches any name.

Example: for (const item of root.elements("item")) { … }

#
element(path: string): XmlNode

The first child element (path as in elements), or null if none.

Example: const name = root.element("customer/name");, if (node.element("memo") != null) { … }

#
childText(path: string, fallback: string = ""): string

The text of the first child element (element(path).text). fallback (default "") if there is no such element.

Example: const name = order.childText("customer/name");

#
descendants(name: string = "*"): XmlNode[]

The descendant elements (children, grandchildren, …) named name (default "*": all), in document order.

Example: root.descendants("item").length

#
addElement(name: string, text: string = ""): XmlNode

Adds a child element and returns it. With text, that text becomes its content.

Example: const item = root.addElement("item"); item.addElement("name", "apple");

#
addText(text: string): XmlNode

Adds a text as a child. Returns this node.

#
addCData(text: string): XmlNode

Adds a CDATA section as a child. Returns this node.

#
addComment(text: string): XmlNode

Adds a comment as a child. Returns this node.

#
append(node: XmlNode): XmlNode

Adds a node (one made with xml.element, or a node of another document) as a child. Returns this node.

#
remove(node: XmlNode): boolean

Removes a child node (the first one if the same node appears twice). true if it was removed.

Example: root.remove(root.element("draft"))

xml.ras

Function xml.element

function element(name: string, text: string = ""): XmlNode

Creates an element (with text, that text becomes its content). Use it for the root of a new document or for elements to append later.

Example: const root = xml.element("orders"); root.addElement("order").setAttr("id", "1");

xml.ras

Function xml.parse

function parse(text: string): XmlNode

Parses an XML string and returns the root element. The XML declaration, <!DOCTYPE>, processing instructions (<?…?>) and comments outside the root are skipped. Entity references (&lt;, &amp;, &#x3042; and so on) are turned into characters. Text nodes of only whitespace (line breaks, indentation) are dropped. Invalid syntax raises an error with the position (line and column).

Example: const root = xml.parse(text);, for (const item of root.elements("item")) debug.print(item.attr("id"), item.childText("name"));

xml.ras

Function xml.stringify

function stringify(node: XmlNode, indent: int = 2, declaration: boolean = false, encoding: string = "utf8"): string

Converts a node to an XML string. indent is the number of spaces of indentation (default 2; no line breaks when 0). Elements with mixed text are not indented inside (so that the text does not change). With declaration: true, an XML declaration (<?xml version="1.0" encoding="UTF-8"?>, with the name of encoding) is put at the start.

Example: const text = xml.stringify(root);, xml.stringify(node, 0)

xml.ras

Function xml.read

function read(p: string, encoding: string = "auto"): XmlNode

Reads an XML file and returns the root element (as parse). When encoding is "auto" (default), the encoding is decided by the BOM, the encoding of the XML declaration (Shift_JIS and so on), and whether the bytes are valid UTF-8, in that order. Other values are as in fs.readText.

Example: const root = xml.read("C:\\data\\orders.xml");

xml.ras

Function xml.write

function write(p: string, node: XmlNode, indent: int = 2, encoding: string = "utf8"): void

Writes a node to an XML file, with an XML declaration at the start (with the name of encoding). encoding is as in fs.writeText (default "utf8": UTF-8 without a BOM). indent is as in stringify (default 2).

Example: xml.write("orders.xml", root), xml.write(path, root, encoding: "shift_jis")

xml.ras