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

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.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 9d786e5 was bc570f4, checked in by lewis, 7 years ago

Refactor CanSASReader/XMLReader to use FileReader? class

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