add readxml function that reads an XML file and returns it as property tree
This commit is contained in:
parent
968c517a71
commit
7b1ac37678
1 changed files with 30 additions and 0 deletions
30
Nasal/io.nas
30
Nasal/io.nas
|
@ -26,3 +26,33 @@ var ifmts = {dir:4, reg:8, lnk:10, sock:12, fifo:1, blk:6, chr:2};
|
||||||
foreach(fmt; keys(ifmts))
|
foreach(fmt; keys(ifmts))
|
||||||
caller(0)[0]["is" ~ fmt] = _gen_ifmt_test(ifmts[fmt]);
|
caller(0)[0]["is" ~ fmt] = _gen_ifmt_test(ifmts[fmt]);
|
||||||
|
|
||||||
|
# Reads an XML file from an absolute path and returns it as property
|
||||||
|
# tree. All nodes are of type STRING, attributes are written as regular
|
||||||
|
# nodes with the optional prefix prepended to the name. If the prefix
|
||||||
|
# is nil, then attributes are ignored. Returns nil on error.
|
||||||
|
var readxml = func(file, prefix = "") {
|
||||||
|
var stack = [[0, ""]];
|
||||||
|
var node = props.Node.new();
|
||||||
|
var tree = node; # prevent GC
|
||||||
|
var start = func(name, attr) {
|
||||||
|
stack[-1][0] += 1; # count children
|
||||||
|
append(stack, [0, ""]);
|
||||||
|
var index = size(node.getChildren(name));
|
||||||
|
node = node.getChild(name, index, 1);
|
||||||
|
if(prefix != nil)
|
||||||
|
foreach(var n; keys(attr))
|
||||||
|
node.getNode(prefix ~ n, 1).setValue(attr[n]);
|
||||||
|
}
|
||||||
|
var end = func(name) {
|
||||||
|
var buf = pop(stack);
|
||||||
|
if(!buf[0] and size(buf[1]))
|
||||||
|
node.setValue(buf[1]);
|
||||||
|
node = node.getParent();
|
||||||
|
}
|
||||||
|
var data = func(d) {
|
||||||
|
stack[-1][1] ~= d;
|
||||||
|
}
|
||||||
|
return parsexml(file, start, end, data) == nil ? nil : tree;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
Loading…
Add table
Reference in a new issue