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