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

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.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since ec72ceb was a235f715, checked in by krzywon, 8 years ago

#500: Final changes to Anton Paar SAXSESS reader.

  • Property mode set to 100644
File size: 9.7 KB
RevLine 
[5ce7f17]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:
[a235f715]73            logging.info(xml_error)
74        except Exception:
75            self.xml = None
76            self.xmldoc = None
77            self.xmlroot = None
78
79    def set_xml_string(self, tag_soup):
80        """
81        Set an XML string as the working XML.
82
83        :param tag_soup: XML formatted string
84        """
85        try:
86            self.xml = tag_soup
87            self.xmldoc = tag_soup
88            self.xmlroot = etree.fromstring(tag_soup)
89        except etree.XMLSyntaxError as xml_error:
[5ce7f17]90            logging.info(xml_error)
91        except Exception:
92            self.xml = None
93            self.xmldoc = None
94            self.xmlroot = None
95
96    def set_schema(self, schema):
97        """
98        Set the schema file and parse
99        """
100        try:
101            self.schema = schema
102            self.schemadoc = etree.parse(self.schema, parser=PARSER)
103        except etree.XMLSyntaxError as xml_error:
104            logging.info(xml_error)
105        except Exception:
106            self.schema = None
107            self.schemadoc = None
108
109    def validate_xml(self):
110        """
111        Checks to see if the XML file meets the schema
112        """
113        valid = True
114        if self.schema is not None:
115            self.parse_schema_and_doc()
116            schema_check = etree.XMLSchema(self.schemadoc)
117            valid = schema_check.validate(self.xmldoc)
118        return valid
119
120    def find_invalid_xml(self):
121        """
122        Finds the first offending element that should not be present in XML file
123        """
124        first_error = ""
125        self.parse_schema_and_doc()
126        schema = etree.XMLSchema(self.schemadoc)
127        try:
128            first_error = schema.assertValid(self.xmldoc)
129        except etree.DocumentInvalid as err:
130            first_error = str(err)
131        return first_error
132
133    def parse_schema_and_doc(self):
134        """
135        Creates a dictionary of the parsed schema and xml files.
136        """
137        self.set_xml_file(self.xml)
138        self.set_schema(self.schema)
139
140    def to_string(self, elem, pretty_print=False, encoding=None):
141        """
142        Converts an etree element into a string
143        """
144        return etree.tostring(elem, pretty_print=pretty_print, \
145                              encoding=encoding)
146
147    def break_processing_instructions(self, string, dic):
148        """
149        Method to break a processing instruction string apart and add to a dict
150
151        :param string: A processing instruction as a string
152        :param dic: The dictionary to save the PIs to
153        """
154        pi_string = string.replace("<?", "").replace("?>", "")
155        split = pi_string.split(" ", 1)
156        pi_name = split[0]
157        attr = split[1]
158        new_pi_name = self._create_unique_key(dic, pi_name)
159        dic[new_pi_name] = attr
160        return dic
161
162    def set_processing_instructions(self):
163        """
164        Take out all processing instructions and create a dictionary from them
165        If there is a default encoding, the value is also saved
166        """
167        dic = {}
168        proc_instr = self.xmlroot.getprevious()
169        while proc_instr is not None:
170            pi_string = self.to_string(proc_instr)
171            if "?>\n<?" in pi_string:
172                pi_string = pi_string.split("?>\n<?")
173            if isinstance(pi_string, str):
174                dic = self.break_processing_instructions(pi_string, dic)
175            elif isinstance(pi_string, list):
176                for item in pi_string:
177                    dic = self.break_processing_instructions(item, dic)
178            proc_instr = proc_instr.getprevious()
179        if 'xml' in dic:
180            self.set_encoding(dic['xml'])
181            del dic['xml']
182        self.processing_instructions = dic
183
184    def set_encoding(self, attr_str):
185        """
186        Find the encoding in the xml declaration and save it as a string
187
188        :param attr_str: All attributes as a string
189            e.g. "foo1="bar1" foo2="bar2" foo3="bar3" ... foo_n="bar_n""
190        """
191        attr_str = attr_str.replace(" = ", "=")
192        attr_list = attr_str.split()
193        for item in attr_list:
194            name_value = item.split("\"=")
195            name = name_value[0].lower()
196            value = name_value[1]
197            if name == "encoding":
198                self.encoding = value
199                return
200        self.encoding = None
201
202    def _create_unique_key(self, dictionary, name, numb=0):
203        """
204        Create a unique key value for any dictionary to prevent overwriting
205        Recurses until a unique key value is found.
206       
207        :param dictionary: A dictionary with any number of entries
208        :param name: The index of the item to be added to dictionary
209        :param numb: The number to be appended to the name, starts at 0
210        """
211        if dictionary.get(name) is not None:
212            numb += 1
213            name = name.split("_")[0]
214            name += "_{0}".format(numb)
215            name = self._create_unique_key(dictionary, name, numb)
216        return name
217
218    def create_tree(self, root):
219        """
220        Create an element tree for processing from an etree element
221
222        :param root: etree Element(s)
223        """
224        return etree.ElementTree(root)
225
226    def create_element_from_string(self, xml_string):
227        """
228        Create an element from an XML string
229
230        :param xml_string: A string of xml
231        """
232        return etree.fromstring(xml_string)
233
234    def create_element(self, name, attrib=None, nsmap=None):
235        """
236        Create an XML element for writing to file
237
238        :param name: The name of the element to be created
239        """
240        if attrib == None:
241            attrib = {}
242        return etree.Element(name, attrib, nsmap)
243
244    def write_text(self, elem, text):
245        """
246        Write text to an etree Element
247
248        :param elem: etree.Element object
249        :param text: text to write to the element
250        """
251        elem.text = text
252        return elem
253
254    def write_attribute(self, elem, attr_name, attr_value):
255        """
256        Write attributes to an Element
257
258        :param elem: etree.Element object
259        :param attr_name: attribute name to write
260        :param attr_value: attribute value to set
261        """
262        attr = elem.attrib
263        attr[attr_name] = attr_value
264
265    def return_processing_instructions(self):
266        """
267        Get all processing instructions saved when loading the document
268
269        :param tree: etree.ElementTree object to write PIs to
270        """
271        pi_list = []
272        if self.processing_instructions is not None:
273            for key in self.processing_instructions:
274                value = self.processing_instructions.get(key)
275                pi_item = etree.ProcessingInstruction(key, value)
276                pi_list.append(pi_item)
277        return pi_list
278
279    def append(self, element, tree):
280        """
281        Append an etree Element to an ElementTree.
282
283        :param element: etree Element to append
284        :param tree: ElementTree object to append to
285        """
286        tree = tree.append(element)
287        return tree
288
289    def ebuilder(self, parent, elementname, text=None, attrib=None):
290        """
291        Use lxml E builder class with arbitrary inputs.
292
293        :param parnet: The parent element to append a child to
294        :param elementname: The name of the child in string form
295        :param text: The element text
296        :param attrib: A dictionary of attribute names to attribute values
297        """
298        text = str(text)
299        if attrib == None:
300            attrib = {}
301        elem = E(elementname, attrib, text)
302        parent = parent.append(elem)
303        return parent
Note: See TracBrowser for help on using the repository browser.