source: sasview/src/sas/sascalc/dataloader/readers/xml_reader.py @ 628acad

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 628acad was b699768, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 9 years ago

Initial commit of the refactored SasCalc? module.

  • Property mode set to 100644
File size: 9.2 KB
Line 
1"""
2    Generic XML read and write utility
3
4    Usage: Either extend xml_reader or add as a class variable.
5"""
6############################################################################
7#This software was developed by the University of Tennessee as part of the
8#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
9#project funded by the US National Science Foundation.
10#If you use DANSE applications to do scientific research that leads to
11#publication, we ask that you acknowledge the use of the software with the
12#following sentence:
13#This work benefited from DANSE software developed under NSF award DMR-0520547.
14#copyright 2008,2009 University of Tennessee
15#############################################################################
16
17import logging
18from lxml import etree
19from lxml.builder import E
20
21PARSER = etree.ETCompatXMLParser(remove_comments=True, remove_pis=False)
22
23class XMLreader():
24    """
25    Generic XML read and write class. Mostly helper functions.
26    Makes reading/writing XML a bit easier than calling lxml libraries directly.
27
28    :Dependencies:
29        This class requires lxml 2.3 or higher.
30    """
31
32    xml = None
33    xmldoc = None
34    xmlroot = None
35    schema = None
36    schemadoc = None
37    encoding = None
38    processing_instructions = None
39
40    def __init__(self, xml=None, schema=None):
41        self.xml = xml
42        self.schema = schema
43        self.processing_instructions = {}
44        if xml is not None:
45            self.set_xml_file(xml)
46        else:
47            self.xmldoc = None
48            self.xmlroot = None
49        if schema is not None:
50            self.set_schema(schema)
51        else:
52            self.schemadoc = None
53
54    def reader(self):
55        """
56        Read in an XML file into memory and return an lxml dictionary
57        """
58        if self.validate_xml():
59            self.xmldoc = etree.parse(self.xml, parser=PARSER)
60        else:
61            raise etree.XMLSchemaValidateError(self, self.find_invalid_xml())
62        return self.xmldoc
63
64    def set_xml_file(self, xml):
65        """
66        Set the XML file and parse
67        """
68        try:
69            self.xml = xml
70            self.xmldoc = etree.parse(self.xml, parser=PARSER)
71            self.xmlroot = self.xmldoc.getroot()
72        except etree.XMLSyntaxError as xml_error:
73            logging.info(xml_error)
74        except Exception:
75            self.xml = None
76            self.xmldoc = None
77            self.xmlroot = None
78
79    def set_schema(self, schema):
80        """
81        Set the schema file and parse
82        """
83        try:
84            self.schema = schema
85            self.schemadoc = etree.parse(self.schema, parser=PARSER)
86        except etree.XMLSyntaxError as xml_error:
87            logging.info(xml_error)
88        except Exception:
89            self.schema = None
90            self.schemadoc = None
91
92    def validate_xml(self):
93        """
94        Checks to see if the XML file meets the schema
95        """
96        valid = True
97        if self.schema is not None:
98            self.parse_schema_and_doc()
99            schema_check = etree.XMLSchema(self.schemadoc)
100            valid = schema_check.validate(self.xmldoc)
101        return valid
102
103    def find_invalid_xml(self):
104        """
105        Finds the first offending element that should not be present in XML file
106        """
107        first_error = ""
108        self.parse_schema_and_doc()
109        schema = etree.XMLSchema(self.schemadoc)
110        try:
111            first_error = schema.assertValid(self.xmldoc)
112        except etree.DocumentInvalid as err:
113            first_error = str(err)
114        return first_error
115
116    def parse_schema_and_doc(self):
117        """
118        Creates a dictionary of the parsed schema and xml files.
119        """
120        self.set_xml_file(self.xml)
121        self.set_schema(self.schema)
122
123    def to_string(self, elem, pretty_print=False, encoding=None):
124        """
125        Converts an etree element into a string
126        """
127        return etree.tostring(elem, pretty_print=pretty_print, \
128                              encoding=encoding)
129
130    def break_processing_instructions(self, string, dic):
131        """
132        Method to break a processing instruction string apart and add to a dict
133
134        :param string: A processing instruction as a string
135        :param dic: The dictionary to save the PIs to
136        """
137        pi_string = string.replace("<?", "").replace("?>", "")
138        split = pi_string.split(" ", 1)
139        pi_name = split[0]
140        attr = split[1]
141        new_pi_name = self._create_unique_key(dic, pi_name)
142        dic[new_pi_name] = attr
143        return dic
144
145    def set_processing_instructions(self):
146        """
147        Take out all processing instructions and create a dictionary from them
148        If there is a default encoding, the value is also saved
149        """
150        dic = {}
151        proc_instr = self.xmlroot.getprevious()
152        while proc_instr is not None:
153            pi_string = self.to_string(proc_instr)
154            if "?>\n<?" in pi_string:
155                pi_string = pi_string.split("?>\n<?")
156            if isinstance(pi_string, str):
157                dic = self.break_processing_instructions(pi_string, dic)
158            elif isinstance(pi_string, list):
159                for item in pi_string:
160                    dic = self.break_processing_instructions(item, dic)
161            proc_instr = proc_instr.getprevious()
162        if 'xml' in dic:
163            self.set_encoding(dic['xml'])
164            del dic['xml']
165        self.processing_instructions = dic
166
167    def set_encoding(self, attr_str):
168        """
169        Find the encoding in the xml declaration and save it as a string
170
171        :param attr_str: All attributes as a string
172            e.g. "foo1="bar1" foo2="bar2" foo3="bar3" ... foo_n="bar_n""
173        """
174        attr_str = attr_str.replace(" = ", "=")
175        attr_list = attr_str.split()
176        for item in attr_list:
177            name_value = item.split("\"=")
178            name = name_value[0].lower()
179            value = name_value[1]
180            if name == "encoding":
181                self.encoding = value
182                return
183        self.encoding = None
184
185    def _create_unique_key(self, dictionary, name, numb=0):
186        """
187        Create a unique key value for any dictionary to prevent overwriting
188        Recurses until a unique key value is found.
189       
190        :param dictionary: A dictionary with any number of entries
191        :param name: The index of the item to be added to dictionary
192        :param numb: The number to be appended to the name, starts at 0
193        """
194        if dictionary.get(name) is not None:
195            numb += 1
196            name = name.split("_")[0]
197            name += "_{0}".format(numb)
198            name = self._create_unique_key(dictionary, name, numb)
199        return name
200
201    def create_tree(self, root):
202        """
203        Create an element tree for processing from an etree element
204
205        :param root: etree Element(s)
206        """
207        return etree.ElementTree(root)
208
209    def create_element_from_string(self, xml_string):
210        """
211        Create an element from an XML string
212
213        :param xml_string: A string of xml
214        """
215        return etree.fromstring(xml_string)
216
217    def create_element(self, name, attrib=None, nsmap=None):
218        """
219        Create an XML element for writing to file
220
221        :param name: The name of the element to be created
222        """
223        if attrib == None:
224            attrib = {}
225        return etree.Element(name, attrib, nsmap)
226
227    def write_text(self, elem, text):
228        """
229        Write text to an etree Element
230
231        :param elem: etree.Element object
232        :param text: text to write to the element
233        """
234        elem.text = text
235        return elem
236
237    def write_attribute(self, elem, attr_name, attr_value):
238        """
239        Write attributes to an Element
240
241        :param elem: etree.Element object
242        :param attr_name: attribute name to write
243        :param attr_value: attribute value to set
244        """
245        attr = elem.attrib
246        attr[attr_name] = attr_value
247
248    def return_processing_instructions(self):
249        """
250        Get all processing instructions saved when loading the document
251
252        :param tree: etree.ElementTree object to write PIs to
253        """
254        pi_list = []
255        if self.processing_instructions is not None:
256            for key in self.processing_instructions:
257                value = self.processing_instructions.get(key)
258                pi_item = etree.ProcessingInstruction(key, value)
259                pi_list.append(pi_item)
260        return pi_list
261
262    def append(self, element, tree):
263        """
264        Append an etree Element to an ElementTree.
265
266        :param element: etree Element to append
267        :param tree: ElementTree object to append to
268        """
269        tree = tree.append(element)
270        return tree
271
272    def ebuilder(self, parent, elementname, text=None, attrib=None):
273        """
274        Use lxml E builder class with arbitrary inputs.
275
276        :param parnet: The parent element to append a child to
277        :param elementname: The name of the child in string form
278        :param text: The element text
279        :param attrib: A dictionary of attribute names to attribute values
280        """
281        text = str(text)
282        if attrib == None:
283            attrib = {}
284        elem = E(elementname, attrib, text)
285        parent = parent.append(elem)
286        return parent
Note: See TracBrowser for help on using the repository browser.