1 | |
---|
2 | # extremely simple XML writer |
---|
3 | # |
---|
4 | # This is to remove libxml2 dependency on platforms where it's |
---|
5 | # difficult to build |
---|
6 | # |
---|
7 | # 2003 Attila Tajti <attis@spacehawks.hu> |
---|
8 | |
---|
9 | class XMLDoc: |
---|
10 | |
---|
11 | def __init__(self, version): |
---|
12 | self.version = version |
---|
13 | self.root_element = None |
---|
14 | |
---|
15 | def saveFile(self, filename): |
---|
16 | f = file(filename, "w") |
---|
17 | f.write('<?xml version="' + self.version + '"?>\n') |
---|
18 | self.root_element._write(f, 0) |
---|
19 | |
---|
20 | def saveFormatFile(self, filename, fmt): |
---|
21 | self.saveFile(filename) |
---|
22 | |
---|
23 | def freeDoc(self): |
---|
24 | pass |
---|
25 | |
---|
26 | class XMLNode: |
---|
27 | |
---|
28 | def __init__(self, name): |
---|
29 | self.name = name |
---|
30 | self.props = [] |
---|
31 | self.children = [] |
---|
32 | self.content = None |
---|
33 | |
---|
34 | def docSetRootElement(self, doc): |
---|
35 | doc.root_element = self |
---|
36 | |
---|
37 | def newChild(self, namespace, name, content): |
---|
38 | if namespace: |
---|
39 | fullname = namespace + ':' + name |
---|
40 | else: |
---|
41 | fullname = name |
---|
42 | child = XMLNode(fullname) |
---|
43 | child.content = content |
---|
44 | self.children.append(child) |
---|
45 | return child |
---|
46 | |
---|
47 | def setProp(self, name, value): |
---|
48 | self.props.append((name, value)) |
---|
49 | |
---|
50 | def _write(self, f, indent): |
---|
51 | #istr = " " * indent |
---|
52 | istr = "\t" * indent |
---|
53 | |
---|
54 | # put together our tag |
---|
55 | tag = self.name |
---|
56 | for prop in self.props: |
---|
57 | name, value = prop |
---|
58 | tag += ' ' + name + '="' + value + '"' |
---|
59 | |
---|
60 | # print tag, or children between tags |
---|
61 | if self.children: |
---|
62 | f.write(istr + '<%s>\n' % tag) |
---|
63 | for child in self.children: |
---|
64 | child._write(f, indent + 1) |
---|
65 | f.write(istr + '</%s>\n' % self.name) |
---|
66 | else: |
---|
67 | f.write(istr + '<%s/>\n' % tag) |
---|
68 | |
---|
69 | def newDoc(version): |
---|
70 | return XMLDoc(version) |
---|
71 | |
---|
72 | def newNode(name): |
---|
73 | return XMLNode(name) |
---|
74 | |
---|
75 | |
---|