[eda8972] | 1 | """ |
---|
[2e3b055] | 2 | Generic XML read and write utility |
---|
| 3 | |
---|
| 4 | Usage: Either extend xml_reader or add as a class variable. |
---|
[eda8972] | 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 | |
---|
[3241dd2] | 17 | import logging |
---|
[eda8972] | 18 | from lxml import etree |
---|
[2e3b055] | 19 | from lxml.builder import E |
---|
[ac5b69d] | 20 | |
---|
| 21 | PARSER = etree.ETCompatXMLParser(remove_comments=True, remove_pis=False) |
---|
[eda8972] | 22 | |
---|
| 23 | class XMLreader(): |
---|
[ac5b69d] | 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 | """ |
---|
[eda8972] | 31 | |
---|
[76cd1ae] | 32 | xml = None |
---|
| 33 | xmldoc = None |
---|
| 34 | xmlroot = None |
---|
| 35 | schema = None |
---|
| 36 | schemadoc = None |
---|
[2e3b055] | 37 | encoding = None |
---|
[ac5b69d] | 38 | processing_instructions = None |
---|
[76cd1ae] | 39 | |
---|
[3241dd2] | 40 | def __init__(self, xml = None, schema = None): |
---|
[eda8972] | 41 | self.xml = xml |
---|
| 42 | self.schema = schema |
---|
[ac5b69d] | 43 | self.processing_instructions = {} |
---|
[eda8972] | 44 | if xml is not None: |
---|
[3241dd2] | 45 | self.set_xml_file(xml) |
---|
[eda8972] | 46 | else: |
---|
| 47 | self.xmldoc = None |
---|
| 48 | self.xmlroot = None |
---|
| 49 | if schema is not None: |
---|
[ac5b69d] | 50 | self.set_schema(schema) |
---|
[eda8972] | 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 | """ |
---|
[ac5b69d] | 58 | if self.validate_xml(): |
---|
| 59 | self.xmldoc = etree.parse(self.xml, parser = PARSER) |
---|
[eda8972] | 60 | else: |
---|
[ac5b69d] | 61 | raise etree.XMLSchemaValidateError(self, self.find_invalid_xml()) |
---|
[eda8972] | 62 | return self.xmldoc |
---|
| 63 | |
---|
[3241dd2] | 64 | def set_xml_file(self, xml): |
---|
[ea67541] | 65 | """ |
---|
| 66 | Set the XML file and parse |
---|
| 67 | """ |
---|
[eda8972] | 68 | try: |
---|
| 69 | self.xml = xml |
---|
[ac5b69d] | 70 | self.xmldoc = etree.parse(self.xml, parser = PARSER) |
---|
[eda8972] | 71 | self.xmlroot = self.xmldoc.getroot() |
---|
[3241dd2] | 72 | except etree.XMLSyntaxError as xml_error: |
---|
| 73 | logging.info(xml_error) |
---|
[17a25d4] | 74 | except Exception: |
---|
[76cd1ae] | 75 | self.xml = None |
---|
| 76 | self.xmldoc = None |
---|
| 77 | self.xmlroot = None |
---|
[eda8972] | 78 | |
---|
[ac5b69d] | 79 | def set_schema(self, schema): |
---|
[ea67541] | 80 | """ |
---|
| 81 | Set the schema file and parse |
---|
| 82 | """ |
---|
[eda8972] | 83 | try: |
---|
| 84 | self.schema = schema |
---|
[ac5b69d] | 85 | self.schemadoc = etree.parse(self.schema, parser = PARSER) |
---|
[3241dd2] | 86 | except etree.XMLSyntaxError as xml_error: |
---|
| 87 | logging.info(xml_error) |
---|
[17a25d4] | 88 | except Exception: |
---|
[76cd1ae] | 89 | self.schema = None |
---|
| 90 | self.schemadoc = None |
---|
[eda8972] | 91 | |
---|
[ac5b69d] | 92 | def validate_xml(self): |
---|
[eda8972] | 93 | """ |
---|
| 94 | Checks to see if the XML file meets the schema |
---|
| 95 | """ |
---|
| 96 | valid = True |
---|
| 97 | if self.schema is not None: |
---|
[ac5b69d] | 98 | self.parse_schema_and_doc() |
---|
| 99 | schema_check = etree.XMLSchema(self.schemadoc) |
---|
| 100 | valid = schema_check.validate(self.xmldoc) |
---|
[eda8972] | 101 | return valid |
---|
| 102 | |
---|
[ac5b69d] | 103 | def find_invalid_xml(self): |
---|
[eda8972] | 104 | """ |
---|
[ea67541] | 105 | Finds the first offending element that should not be present in XML file |
---|
[eda8972] | 106 | """ |
---|
[ac5b69d] | 107 | first_error = "" |
---|
| 108 | self.parse_schema_and_doc() |
---|
[eda8972] | 109 | schema = etree.XMLSchema(self.schemadoc) |
---|
| 110 | try: |
---|
[ac5b69d] | 111 | first_error = schema.assertValid(self.xmldoc) |
---|
[3241dd2] | 112 | except etree.DocumentInvalid as err: |
---|
| 113 | first_error = str(err) |
---|
[ac5b69d] | 114 | return first_error |
---|
[eda8972] | 115 | |
---|
[ac5b69d] | 116 | def parse_schema_and_doc(self): |
---|
[eda8972] | 117 | """ |
---|
| 118 | Creates a dictionary of the parsed schema and xml files. |
---|
| 119 | """ |
---|
[ac5b69d] | 120 | self.set_xml_file(self.xml) |
---|
| 121 | self.set_schema(self.schema) |
---|
[ea67541] | 122 | |
---|
[3241dd2] | 123 | def to_string(self, elem, pretty_print=False, encoding=None): |
---|
[2e3b055] | 124 | """ |
---|
| 125 | Converts an etree element into a string |
---|
| 126 | """ |
---|
[3241dd2] | 127 | return etree.tostring(elem, pretty_print = pretty_print, \ |
---|
| 128 | encoding = encoding) |
---|
[2e3b055] | 129 | |
---|
| 130 | def break_processing_instructions(self, string, dic): |
---|
[ea67541] | 131 | """ |
---|
[2e3b055] | 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 |
---|
[ea67541] | 136 | """ |
---|
[2e3b055] | 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 |
---|
[ea67541] | 144 | |
---|
[ac5b69d] | 145 | def set_processing_instructions(self): |
---|
[ea67541] | 146 | """ |
---|
| 147 | Take out all processing instructions and create a dictionary from them |
---|
[2e3b055] | 148 | If there is a default encoding, the value is also saved |
---|
[ea67541] | 149 | """ |
---|
| 150 | dic = {} |
---|
[ac5b69d] | 151 | proc_instr = self.xmlroot.getprevious() |
---|
| 152 | while proc_instr is not None: |
---|
| 153 | pi_string = self.to_string(proc_instr) |
---|
[2e3b055] | 154 | if "?>\n<?" in pi_string: |
---|
| 155 | pi_string = pi_string.split("?>\n<?") |
---|
[ea67541] | 156 | if isinstance(pi_string, str): |
---|
[2e3b055] | 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) |
---|
[ac5b69d] | 161 | proc_instr = proc_instr.getprevious() |
---|
[2e3b055] | 162 | if 'xml' in dic: |
---|
[ac5b69d] | 163 | self.set_encoding(dic['xml']) |
---|
[2e3b055] | 164 | del dic['xml'] |
---|
[ac5b69d] | 165 | self.processing_instructions = dic |
---|
[ea67541] | 166 | |
---|
[ac5b69d] | 167 | def set_encoding(self, attr_str): |
---|
[2e3b055] | 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 | |
---|
[ac5b69d] | 185 | def _create_unique_key(self, dictionary, name, numb = 0): |
---|
[ea67541] | 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 |
---|
[ac5b69d] | 192 | :param numb: The number to be appended to the name, starts at 0 |
---|
[ea67541] | 193 | """ |
---|
| 194 | if dictionary.get(name) is not None: |
---|
[ac5b69d] | 195 | numb += 1 |
---|
[ea67541] | 196 | name = name.split("_")[0] |
---|
[ac5b69d] | 197 | name += "_{0}".format(numb) |
---|
| 198 | name = self._create_unique_key(dictionary, name, numb) |
---|
[ea67541] | 199 | return name |
---|
| 200 | |
---|
[f44b076] | 201 | def create_tree(self, root): |
---|
| 202 | """ |
---|
[2e3b055] | 203 | Create an element tree for processing from an etree element |
---|
[f44b076] | 204 | |
---|
[2e3b055] | 205 | :param root: etree Element(s) |
---|
[f44b076] | 206 | """ |
---|
| 207 | return etree.ElementTree(root) |
---|
| 208 | |
---|
[ac5b69d] | 209 | def create_element_from_string(self, xml_string): |
---|
[2e3b055] | 210 | """ |
---|
| 211 | Create an element from an XML string |
---|
| 212 | |
---|
[ac5b69d] | 213 | :param xml_string: A string of xml |
---|
[2e3b055] | 214 | """ |
---|
[ac5b69d] | 215 | return etree.fromstring(xml_string) |
---|
[2e3b055] | 216 | |
---|
[ac5b69d] | 217 | def create_element(self, name, attrib=None, nsmap=None): |
---|
[f44b076] | 218 | """ |
---|
| 219 | Create an XML element for writing to file |
---|
| 220 | |
---|
| 221 | :param name: The name of the element to be created |
---|
| 222 | """ |
---|
[ac5b69d] | 223 | if attrib == None: |
---|
| 224 | attrib = {} |
---|
[2e3b055] | 225 | return etree.Element(name, attrib, nsmap) |
---|
[f44b076] | 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 |
---|
[2e3b055] | 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 = [] |
---|
[ac5b69d] | 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) |
---|
[2e3b055] | 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 | |
---|
[ac5b69d] | 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 | """ |
---|
[2e3b055] | 281 | text = str(text) |
---|
[ac5b69d] | 282 | if attrib == None: |
---|
| 283 | attrib = {} |
---|
[2e3b055] | 284 | elem = E(elementname, attrib, text) |
---|
| 285 | parent = parent.append(elem) |
---|
| 286 | return parent |
---|
[17a25d4] | 287 | |
---|