1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
use xml = format::fastxml;
use sort;
use os;
use fmt;
use strings;
type node = struct {
name: str,
attributes: []str,
has_text: bool,
children: []*node,
};
fn add_attr(n: *node, attr: xml::attribute) void = {
for (let i = 0z; i < len(n.attributes); i += 1) {
if (n.attributes[i] == attr.0) return;
};
append(n.attributes, strings::dup(attr.0));
};
fn add_text(n: *node, text: str) void = {
const clean = strings::trim(text);
n.has_text ||= len(clean) > 0;
};
fn get_node(n: *node, name: str) *node = {
for (let i = 0z; i < len(n.children); i += 1) {
if (n.children[i].name == name)
return n.children[i];
};
let new = alloc(node { name = strings::dup(name), ... });
append(n.children, new);
return new;
};
fn print(n: *node, indent: size) void = {
for (let i = 0z; i < indent; i += 1) fmt::print("> ")!;
fmt::print(n.name)!;
if (n.has_text) fmt::print("+")!;
fmt::print(" [")!;
for (let i = 0z; i < len(n.attributes); i += 1) {
fmt::printf("{}{}", if (i == 0) "" else " ", n.attributes[i])!;
};
fmt::println("]")!;
for (let i = 0z; i < len(n.children); i += 1) {
print(n.children[i], indent + 1);
};
};
export fn main() void = {
if (len(os::args) - 1 < 1) {
fmt::fatal("Usage: xmltree <file.xml>");
};
const file = os::open(os::args[1])!;
const parser = xml::parse(file)!;
defer xml::parser_free(parser);
let tree = null: *node;
defer free(tree); // memory leaks!
let stack: []*node = [];
defer free(stack);
for (true) {
const token = match (xml::scan(parser)!) {
case let t: xml::token =>
yield t;
case void =>
break;
};
match (token) {
case let start: xml::elementstart =>
if (len(stack) == 0) {
tree = alloc(node {
name = strings::dup(start),
...
});
append(stack, tree);
} else {
let current = stack[len(stack) - 1];
append(stack, get_node(current, start));
};
case let end: xml::elementend =>
//fmt::printfln("stack => {}", stack[len(stack) - 1].name)!;
//fmt::printfln("file => {}", end)!;
assert(end == stack[len(stack) - 1].name);
delete(stack[len(stack) - 1]);
if (len(stack) == 0) break;
case let attr: xml::attribute =>
let current = stack[len(stack) - 1];
add_attr(current, attr);
case let text: xml::text =>
let current = stack[len(stack) - 1];
add_text(current, text);
};
};
print(tree, 0);
};
|