Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/xmlio.py
blob: 86b3b9e8fc260f80f0ddc5925cb3d44770194aa1 (plain)
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
#! /usr/bin/env python
# -*- coding: utf-8 -*-

# reads and writes xml files
# output files indented

import xml.etree.ElementTree as ET

#tree = Xmlio(path)
#elem = tree.getroot()
#tree.save(path)   --- uses root of tree
#tree.save(path,root=elem) -- saves tree from supplied root element

class Xmlio():

    def __init__(self, path = None, root = None):
        print 'params: path=', path, 'root=', root
        if root:
            if path:
                self.root = root
                self.tree = ET.ElementTree(self.root)
            else:
                self.root = ET.Element(root)
                self.tree = ET.ElementTree(self.root)
        else:
            try:
                self.tree = ET.parse(path)
            except: 
                print "error parsing xml file", path
                return
            self.root = self.tree.getroot()

    def getroot(self, root = ''):
        if not root:
           return self.root
        else:
           return ET.Element(root)

    def indent(self, elem, level=0):
        i = "\n" + level * "  "
        if len(elem):
            if not elem.text or not elem.text.strip():
                elem.text = i + "  "
            for elem in elem:
                self.indent(elem, level+1)
            if not elem.tail or not elem.tail.strip():
                elem.tail = i
        else:
            if level and (not elem.tail or not elem.tail.strip()):
                elem.tail = i

    def save(self,  path, root = ''):
        if not root:
            root = self.root
        self.indent(root)  #prettyprint
        ET.ElementTree(root).write(path)