Table of Contents
XML
This is the documentation of the XML module that enables user programs to parse XML strings and to define their own native XML tags. For instance:
Use import xml from "hop:xml" or
require(hop.xml)`
This module also implements an XML pre-processor ables to load complete XML documents.
Use require("./example.xml", hop.xml)
This will return the root element (as created by createElement
) contained
in the XML document ./example.xml
.
Functions
xml.createElement(tag, attributes, children)
Creates a native tag
xml element. Its attributes are described
by the JavaScript attributes
object. The children must be
a JavaScript array.
xml.parseSync(string|fd])
Parses a string representing a list of XML tags and returns an array of JavaScript values. The argument is either the string to be parsed or a file description (an integer). The values are either strings, or objects with three properties:
tag
, the xml tag represented as a string;attributes
, a JavaScript object where each property correspond to an xml element attribute;children
, the xml element children stored in an array.
xml.parse(string|fd, [callback])
Parse a string asynchronously. If no callback is provided, this function
returns a promise that resolve with the parsed value. If provided callback
must be a procedure of two arguments: an error
, and a value
. In success,
error
if false
.
Example
example.js
"use strict";
const xml = require( hop.xml );
function XML( attrs, ... nodes ) {
return xml.createElement( "xml", attrs, nodes );
}
function BLOCK( attrs, ... nodes ) {
return xml.createElement( "block", attrs, nodes );
}
function FIELD( attrs, ... nodes ) {
return xml.createElement( "field", attrs, nodes );
}
const decl = <xml xmlns="https://developers.google.com/blockly/xml" id="toolbox" style="display: none">
<block type="controls_if"></block>
<block type="logic_compare"></block>
<block type="controls_repeat_ext"></block>
<block type="math_number">
<field name="NUM">123</field>
</block>
<block type="math_arithmetic"></block>
<block type="text"></block>
<block type="text_print"></block>
</xml>;
console.log( decl.toString() );
parse.js
"use strict";
import { parseSync as XMLparse } from "hop:xml";
console.log(XMLparse("1"));
// [ '1' ]
console.log(XMLparse("foo"));
// [ 'foo' ]
console.log(XMLparse("<el/>"));
// [ { tag: 'el', attributes: {}, children: [] } ]
console.log(XMLparse("<el>foo</el>"));
// [ { tag: 'el', attributes: {}, children: [ 'foo' ] } ]
console.log(XMLparse('<el id="id1">foo</el>'));
// [ { tag: 'el', attributes: { id: 'id1' }, children: [ 'foo' ] } ]
console.log(XMLparse('<els><el id="id1">foo</el><el id="id2">bar</el></els>'));
// [ { tag: 'els',
// attributes: {},
// children: [ { tag: 'el', attributes: { id: 'id1' }, children: [ 'foo' ] },
// { tag: 'el', attributes: { id: 'id2' }, children: [ 'bar' ] } ] } ]