3b43b86660cd873bd0afb859c79ea921b3ec25e1
[debian/gnuradio] / grc / src / grc / ParseXML.py
1 """
2 Copyright 2008 Free Software Foundation, Inc.
3 This file is part of GNU Radio
4
5 GNU Radio Companion is free software; you can redistribute it and/or
6 modify it under the terms of the GNU General Public License
7 as published by the Free Software Foundation; either version 2
8 of the License, or (at your option) any later version.
9
10 GNU Radio Companion is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18 """
19 ##@package grc.gui.ParseXML
20 #Parse xml files to nested data and vice-versa.
21 #@author Josh Blum
22
23 from lxml import etree
24 from Utils import odict
25
26 XMLSyntaxError = etree.XMLSyntaxError
27
28 def validate_dtd(xml_file, dtd_file=None):
29         """!
30         Validate an xml file against its dtd.
31         @param xml_file the xml file
32         @param dtd_file the optional dtd file
33         @throws Exception validation fails
34         """
35         if dtd_file:
36                 dtd = etree.DTD(dtd_file)
37                 xml = etree.parse(xml_file)
38                 if not dtd.validate(xml.getroot()):
39                         raise XMLSyntaxError, '\n'.join(map(str, dtd.error_log.filter_from_errors()))
40         else:
41                 parser = etree.XMLParser(dtd_validation=True)
42                 xml = etree.parse(xml_file, parser=parser)
43                 if parser.error_log:
44                         raise XMLSyntaxError, '\n'.join(map(str, parser.error_log.filter_from_errors()))
45
46 def from_file(xml_file):
47         """!
48         Create nested data from an xml file using the from xml helper.
49         @param xml_file the xml file path
50         @return the nested data
51         """
52         xml = etree.parse(xml_file).getroot()
53         return _from_file(xml)
54
55 def _from_file(xml):
56         """!
57         Recursivly parse the xml tree into nested data format.
58         @param xml the xml tree
59         @return the nested data
60         """
61         tag = xml.tag
62         if not len(xml):
63                 return odict({tag: xml.text or ''}) #store empty tags (text is None) as empty string
64         nested_data = odict()
65         for elem in xml:
66                 key, value = _from_file(elem).items()[0]
67                 if nested_data.has_key(key): nested_data[key].append(value)
68                 else: nested_data[key] = [value]
69         #delistify if the length of values is 1
70         for key, values in nested_data.iteritems():
71                 if len(values) == 1: nested_data[key] = values[0]
72         return odict({tag: nested_data})
73
74 def to_file(nested_data, xml_file):
75         """!
76         Write an xml file and use the to xml helper method to load it.
77         @param nested_data the nested data
78         @param xml_file the xml file path
79         """
80         xml = _to_file(nested_data)[0]
81         open(xml_file, 'w').write(etree.tostring(xml, xml_declaration=True, pretty_print=True))
82
83 def _to_file(nested_data):
84         """!
85         Recursivly parse the nested data into xml tree format.
86         @param nested_data the nested data
87         @return the xml tree filled with child nodes
88         """
89         nodes = list()
90         for key, values in nested_data.iteritems():
91                 #listify the values if not a list
92                 if not isinstance(values, (list, set, tuple)):
93                         values = [values]
94                 for value in values:
95                         node = etree.Element(key)
96                         if isinstance(value, (str, unicode)): node.text = value
97                         else: node.extend(_to_file(value))
98                         nodes.append(node)
99         return nodes
100
101 if __name__ == '__main__':
102         """Use the main method to test parse xml's functions."""
103         pass