Python xml.etree.cElementTree.Element() Examples
The following are 30
code examples of xml.etree.cElementTree.Element().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
xml.etree.cElementTree
, or try the search function
.
Example #1
Source File: cifar_data_processing.py From batch-shipyard with MIT License | 6 votes |
def saveMean(fname, data): root = et.Element('opencv_storage') et.SubElement(root, 'Channel').text = '3' et.SubElement(root, 'Row').text = str(IMGSIZE) et.SubElement(root, 'Col').text = str(IMGSIZE) meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix') et.SubElement(meanImg, 'rows').text = '1' et.SubElement(meanImg, 'cols').text = str(IMGSIZE * IMGSIZE * 3) et.SubElement(meanImg, 'dt').text = 'f' et.SubElement(meanImg, 'data').text = ' '.join(['%e' % n for n in np.reshape(data, (IMGSIZE * IMGSIZE * 3))]) tree = et.ElementTree(root) tree.write(fname) x = xml.dom.minidom.parse(fname) with open(fname, 'w') as f: f.write(x.toprettyxml(indent = ' '))
Example #2
Source File: random_manifest.py From Obfuscapk with MIT License | 6 votes |
def scramble_xml_element(self, element: Element): children = [] # Get the children of the current element. for child in element: children.append(child) # Remove the children from the current element (they will be added later # in a different order). for child in children: element.remove(child) # Shuffle the order of the children of the element and add them again to # the element. Then repeat the scramble operation recursively. random.shuffle(children) for child in children: element.append(child) self.scramble_xml_element(child)
Example #3
Source File: cifar_prepare.py From ngraph-python with Apache License 2.0 | 6 votes |
def saveMean(fname, data): root = et.Element('opencv_storage') et.SubElement(root, 'Channel').text = '3' et.SubElement(root, 'Row').text = str(imgSize) et.SubElement(root, 'Col').text = str(imgSize) meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix') et.SubElement(meanImg, 'rows').text = '1' et.SubElement(meanImg, 'cols').text = str(imgSize * imgSize * 3) et.SubElement(meanImg, 'dt').text = 'f' et.SubElement(meanImg, 'data').text = ' '.join( ['%e' % n for n in np.reshape(data, (imgSize * imgSize * 3))] ) tree = et.ElementTree(root) tree.write(fname) x = xml.dom.minidom.parse(fname) with open(fname, 'w') as f: f.write(x.toprettyxml(indent=' '))
Example #4
Source File: random_manifest.py From Obfuscapk with MIT License | 6 votes |
def remove_xml_duplicates(self, root: Element): # Recursively eliminate duplicates starting from children nodes. for element in root: self.remove_xml_duplicates(element) non_duplicates = [] elements_to_remove = [] # Find duplicate nodes which have the same parent node. for element in root: if any(self.xml_elements_equal(element, nd) for nd in non_duplicates): elements_to_remove.append(element) else: non_duplicates.append(element) # Remove existing duplicates at this level. for element_to_remove in elements_to_remove: root.remove(element_to_remove)
Example #5
Source File: freeze_command.py From openSUSE-release-tools with GNU General Public License v2.0 | 6 votes |
def create_bootstrap_aggregate_file(self): url = self.api.makeurl(['source', self.prj, 'bootstrap-copy', '_aggregate']) root = ET.Element('aggregatelist') a = ET.SubElement(root, 'aggregate', {'project': '{}:0-Bootstrap'.format(self.api.crings)}) for package in self.bootstrap_packages(): p = ET.SubElement(a, 'package') p.text = package ET.SubElement(a, 'repository', {'target': 'bootstrap_copy', 'source': 'standard'}) ET.SubElement(a, 'repository', {'target': 'standard', 'source': 'nothing'}) ET.SubElement(a, 'repository', {'target': 'images', 'source': 'nothing'}) self.api.retried_PUT(url, ET.tostring(root))
Example #6
Source File: document.py From SEM with MIT License | 6 votes |
def from_xml(cls, xml, chunks_to_load=None, load_subtypes=True, type_separator=u"."): if sem.misc.is_string(xml): data = ET.parse(xml) elif isinstance(xml, ET.ElementTree): data = xml elif isinstance(xml, type(ET.Element("a"))): # did not ind a better way to do this data = xml else: raise TypeError("Invalid type for loading XML-SEM document: {0}".format(type(xml))) root = data.getroot() if root.tag != "sem": raise ValueError("Not sem xml file type: '{0}'".format(root.tag)) doc_list = [] for document in list(root): doc_list.append(Document.from_xml(document)) return SEMCorpus(doc_list)
Example #7
Source File: 2_data_to_pascal_xml.py From face-detection-ssd-mobilenet with Apache License 2.0 | 6 votes |
def newXMLPASCALfile(imageheight, imagewidth, path, basename): # print(filename) annotation = ET.Element("annotation", verified="yes") ET.SubElement(annotation, "folder").text = "images" ET.SubElement(annotation, "filename").text = basename ET.SubElement(annotation, "path").text = path source = ET.SubElement(annotation, "source") ET.SubElement(source, "database").text = "test" size = ET.SubElement(annotation, "size") ET.SubElement(size, "width").text = str(imagewidth) ET.SubElement(size, "height").text = str(imageheight) ET.SubElement(size, "depth").text = "3" ET.SubElement(annotation, "segmented").text = "0" tree = ET.ElementTree(annotation) # tree.write("filename.xml") return tree
Example #8
Source File: random_manifest.py From Obfuscapk with MIT License | 6 votes |
def indent_xml(self, element: Element, level=0): indentation = '\n' + level * ' ' if len(element): if not element.text or not element.text.strip(): element.text = indentation + ' ' if not element.tail or not element.tail.strip(): element.tail = indentation for element in element: self.indent_xml(element, level + 1) if not element.tail or not element.tail.strip(): element.tail = indentation else: if level and (not element.tail or not element.tail.strip()): element.tail = indentation # https://stackoverflow.com/a/27550126/5268548
Example #9
Source File: wider_voc.py From hand-detection.PyTorch with MIT License | 6 votes |
def __call__(self, target): """ Arguments: target (annotation) : the target annotation to be made usable will be an ET.Element Returns: a list containing lists of bounding boxes [bbox coords, class name] """ res = np.empty((0, 5)) for obj in target.iter('object'): difficult = int(obj.find('difficult').text) == 1 if not self.keep_difficult and difficult: continue name = obj.find('name').text.lower().strip() bbox = obj.find('bndbox') pts = ['xmin', 'ymin', 'xmax', 'ymax'] bndbox = [] for i, pt in enumerate(pts): cur_pt = int(bbox.find(pt).text) bndbox.append(cur_pt) label_idx = self.class_to_ind[name] bndbox.append(label_idx) res = np.vstack((res, bndbox)) # [xmin, ymin, xmax, ymax, label_ind] return res
Example #10
Source File: printers.py From py-lua-parser with MIT License | 6 votes |
def visit(self, node): xml_node = ElementTree.Element(node.display_name) # attributes for attr, attrValue in node.__dict__.items(): if not attr.startswith('_') and attrValue is not None: xml_attr = ElementTree.SubElement(xml_node, attr) child_node = self.visit(attrValue) if type(child_node) is str: xml_attr.text = child_node elif type(child_node) is list: xml_attr.extend(child_node) else: xml_attr.append(child_node) return xml_node
Example #11
Source File: random_manifest.py From Obfuscapk with MIT License | 6 votes |
def xml_elements_equal(self, one: Element, other: Element) -> bool: if type(one) != type(other): return False if one.tag != other.tag: return False if one.text and other.text: if one.text.strip() != other.text.strip(): return False elif one.text != other.text: return False if one.tail and other.tail: if one.tail.strip() != other.tail.strip(): return False elif one.tail != other.tail: return False if one.attrib != other.attrib: return False if len(one) != len(other): return False return all(self.xml_elements_equal(e1, e2) for e1, e2 in zip(one, other))
Example #12
Source File: utils.py From script.tvguide.fullscreen with GNU General Public License v2.0 | 5 votes |
def generate_settings_file(target_path): source_path = xbmc.translatePath( os.path.join(ADDON.getAddonInfo('path'), 'resources', 'settings.xml')) root_target = ceT.Element("settings") tree_source = eT.parse(source_path) root_source = tree_source.getroot() for item in root_source.findall('category'): for setting in item.findall('setting'): if 'id' in setting.attrib: value = '' if 'default' in setting.attrib: value = setting.attrib['default'] ceT.SubElement(root_target, 'setting', id=setting.attrib['id'], value=value) tree_target = ceT.ElementTree(root_target) f = open(target_path, 'w') tree_target.write(f) f.close()
Example #13
Source File: export.py From rosreestr2coord with MIT License | 5 votes |
def coords2kml(coords, attrs): if len(coords): kml = ET.Element("kml", attrib={"xmlns": "http://www.opengis.net/kml/2.2"}) doc = ET.SubElement(kml, "Document") folder = ET.SubElement(doc, "Folder") ET.SubElement(folder, "name").text = "test" placemark = ET.SubElement(folder, "Placemark") style = ET.SubElement(placemark, "Style") line_style = ET.SubElement(style, "LineStyle") ET.SubElement(line_style, "color").text = "ff0000ff" poly_style = ET.SubElement(style, "PolyStyle") ET.SubElement(poly_style, "fill").text = "0" multi_geometry = ET.SubElement(placemark, "MultiGeometry") for i in range(len(coords)): polygon = ET.SubElement(multi_geometry, "Polygon") for j in range(len(coords[i])): if j: boundary = ET.SubElement(polygon, "outerBoundaryIs") else: # for holes boundary = ET.SubElement(polygon, "innerBoundaryIs") xy = coords[i][j] xy.append(xy[0]) linear_ring = ET.SubElement(boundary, "LinearRing") ET.SubElement(linear_ring, "coordinates").text = ' '.join( map(lambda c: ','.join(map(str, c)), xy) ) return ET.tostring(kml, encoding='utf8', method='xml') return False
Example #14
Source File: workflow.py From alfred-brightness with MIT License | 5 votes |
def send_feedback(self): """Print stored items to console/Alfred as XML.""" root = ET.Element('items') for item in self._items: root.append(item.elem) sys.stdout.write('<?xml version="1.0" encoding="utf-8"?>\n') sys.stdout.write(ET.tostring(root).encode('utf-8')) sys.stdout.flush() #################################################################### # Updating methods ####################################################################
Example #15
Source File: scheme.py From splunk-ref-pas-code with Apache License 2.0 | 5 votes |
def to_xml(self): """Creates an ``ET.Element`` representing self, then returns it. :returns root, an ``ET.Element`` representing this scheme. """ root = ET.Element("scheme") ET.SubElement(root, "title").text = self.title # add a description subelement if it's defined if self.description is not None: ET.SubElement(root, "description").text = self.description # add all other subelements to this Scheme, represented by (tag, text) subelements = [ ("use_external_validation", self.use_external_validation), ("use_single_instance", self.use_single_instance), ("streaming_mode", self.streaming_mode) ] for name, value in subelements: ET.SubElement(root, name).text = str(value).lower() endpoint = ET.SubElement(root, "endpoint") args = ET.SubElement(endpoint, "args") # add arguments as subelements to the <args> element for arg in self.arguments: arg.add_to_document(args) return root
Example #16
Source File: event.py From splunk-ref-pas-code with Apache License 2.0 | 5 votes |
def write_to(self, stream): """Write an XML representation of self, an ``Event`` object, to the given stream. The ``Event`` object will only be written if its data field is defined, otherwise a ``ValueError`` is raised. :param stream: stream to write XML to. """ if self.data is None: raise ValueError("Events must have at least the data field set to be written to XML.") event = ET.Element("event") if self.stanza is not None: event.set("stanza", self.stanza) event.set("unbroken", str(int(self.unbroken))) # if a time isn't set, let Splunk guess by not creating a <time> element if self.time is not None: ET.SubElement(event, "time").text = str(self.time) # add all other subelements to this Event, represented by (tag, text) subelements = [ ("source", self.source), ("sourcetype", self.sourceType), ("index", self.index), ("host", self.host), ("data", self.data) ] for node, value in subelements: if value is not None: ET.SubElement(event, node).text = value if self.done is not None: ET.SubElement(event, "done") stream.write(ET.tostring(event)) stream.flush()
Example #17
Source File: voc0712.py From EfficientDet.Pytorch with MIT License | 5 votes |
def __call__(self, target, width, height): """ Arguments: target (annotation) : the target annotation to be made usable will be an ET.Element Returns: a list containing lists of bounding boxes [bbox coords, class name] """ res = [] for obj in target.iter('object'): difficult = int(obj.find('difficult').text) == 1 if not self.keep_difficult and difficult: continue name = obj.find('name').text.lower().strip() bbox = obj.find('bndbox') pts = ['xmin', 'ymin', 'xmax', 'ymax'] bndbox = [] for i, pt in enumerate(pts): cur_pt = float(bbox.find(pt).text) - 1 # scale height or width # cur_pt = cur_pt / width if i % 2 == 0 else cur_pt / height bndbox.append(cur_pt) label_idx = self.class_to_ind[name] bndbox.append(label_idx) res += [bndbox] # [xmin, ymin, xmax, ymax, label_ind] # img_id = target.find('filename').text[:-4] return res # [[xmin, ymin, xmax, ymax, label_ind], ... ]
Example #18
Source File: argument.py From splunk-ref-pas-code with Apache License 2.0 | 5 votes |
def add_to_document(self, parent): """Adds an ``Argument`` object to this ElementTree document. Adds an <arg> subelement to the parent element, typically <args> and sets up its subelements with their respective text. :param parent: An ``ET.Element`` to be the parent of a new <arg> subelement :returns: An ``ET.Element`` object representing this argument. """ arg = ET.SubElement(parent, "arg") arg.set("name", self.name) if self.description is not None: ET.SubElement(arg, "description").text = self.description if self.validation is not None: ET.SubElement(arg, "validation").text = self.validation # add all other subelements to this Argument, represented by (tag, text) subelements = [ ("data_type", self.data_type), ("required_on_edit", self.required_on_edit), ("required_on_create", self.required_on_create) ] for name, value in subelements: ET.SubElement(arg, name).text = str(value).lower() return arg
Example #19
Source File: argument.py From SplunkForPCAP with MIT License | 5 votes |
def add_to_document(self, parent): """Adds an ``Argument`` object to this ElementTree document. Adds an <arg> subelement to the parent element, typically <args> and sets up its subelements with their respective text. :param parent: An ``ET.Element`` to be the parent of a new <arg> subelement :returns: An ``ET.Element`` object representing this argument. """ arg = ET.SubElement(parent, "arg") arg.set("name", self.name) if self.title is not None: ET.SubElement(arg, "title").text = self.title if self.description is not None: ET.SubElement(arg, "description").text = self.description if self.validation is not None: ET.SubElement(arg, "validation").text = self.validation # add all other subelements to this Argument, represented by (tag, text) subelements = [ ("data_type", self.data_type), ("required_on_edit", self.required_on_edit), ("required_on_create", self.required_on_create) ] for name, value in subelements: ET.SubElement(arg, name).text = str(value).lower() return arg
Example #20
Source File: vocdataset.py From ASFF with GNU General Public License v3.0 | 5 votes |
def __call__(self, target): """ Arguments: target (annotation) : the target annotation to be made usable will be an ET.Element Returns: a list containing lists of bounding boxes [bbox coords, class name] """ res = np.empty((0,5)) for obj in target.iter('object'): difficult = int(obj.find('difficult').text) == 1 if not self.keep_difficult and difficult: continue name = obj.find('name').text.lower().strip() bbox = obj.find('bndbox') pts = ['xmin', 'ymin', 'xmax', 'ymax'] bndbox = [] for i, pt in enumerate(pts): cur_pt = int(bbox.find(pt).text) - 1 # scale height or width #cur_pt = cur_pt / width if i % 2 == 0 else cur_pt / height bndbox.append(cur_pt) label_idx = self.class_to_ind[name] bndbox.append(label_idx) res = np.vstack((res,bndbox)) # [xmin, ymin, xmax, ymax, label_ind] # img_id = target.find('filename').text[:-4] return res # [[xmin, ymin, xmax, ymax, label_ind], ... ]
Example #21
Source File: freeze_command.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def freeze_prjlinks(self): sources = {} flink = ET.Element('frozenlinks') for lprj in self.projectlinks: fl = ET.SubElement(flink, 'frozenlink', {'project': lprj}) sources = self.receive_sources(lprj, sources, fl) url = self.api.makeurl(['source', self.prj, '_project', '_frozenlinks'], {'meta': '1'}) self.api.retried_PUT(url, ET.tostring(flink))
Example #22
Source File: freeze_command.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def create_bootstrap_aggregate_meta(self): url = self.api.makeurl(['source', self.prj, 'bootstrap-copy', '_meta']) root = ET.Element('package', {'project': self.prj, 'name': 'bootstrap-copy'}) ET.SubElement(root, 'title') ET.SubElement(root, 'description') f = ET.SubElement(root, 'build') # this one is to toggle ET.SubElement(f, 'disable', {'repository': 'bootstrap_copy'}) # this one is the global toggle ET.SubElement(f, 'disable') self.api.retried_PUT(url, ET.tostring(root))
Example #23
Source File: freeze_command.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def set_bootstrap_copy(self): url = self.api.makeurl(['source', self.prj, '_meta']) f = self.api.retried_GET(url) oldmeta = ET.parse(f).getroot() meta = ET.fromstring(self.prj_meta_for_bootstrap_copy(self.prj)) meta.find('title').text = oldmeta.find('title').text meta.find('description').text = oldmeta.find('description').text for person in oldmeta.findall('person'): # the xml has a fixed structure meta.insert(2, ET.Element('person', role=person.get('role'), userid=person.get('userid'))) self.api.retried_PUT(url, ET.tostring(meta))
Example #24
Source File: core.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def create_delete_request(apiurl, target_project, target_package=None, message=None): if not message: message = message_suffix('created') request = ETL.Element('request') state = ETL.Element('state') state.set('name', 'new') request.append(state) description = ETL.Element('description') description.text = message request.append(description) action = ETL.Element('action') action.set('type', 'delete') request.append(action) target = ETL.Element('target') target.set('project', target_project) if target_package: target.set('package', target_package) action.append(target) url = makeurl(apiurl, ['request'], {'cmd': 'create'}) root = ETL.parse(http_POST(url, data=ETL.tostring(request))).getroot() return root.get('id') # Should exist within osc.core like create_submit_request(), but rather it was # duplicated in osc.commandline.
Example #25
Source File: core.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def attribute_value_save(apiurl, project, name, value, namespace='OSRT', package=None): root = ET.Element('attributes') attribute = ET.SubElement(root, 'attribute') attribute.set('namespace', namespace) attribute.set('name', name) ET.SubElement(attribute, 'value').text = value # The OBS API of attributes is super strange, POST to update. url = makeurl(apiurl, list(filter(None, ['source', project, package, '_attribute']))) http_POST(url, data=ET.tostring(root))
Example #26
Source File: freeze_command.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def freeze_prjlinks(self): sources = {} flink = ET.Element('frozenlinks') for lprj in self.projectlinks: fl = ET.SubElement(flink, 'frozenlink', {'project': lprj}) sources = self.receive_sources(lprj, sources, fl) url = self.api.makeurl(['source', self.prj, '_project', '_frozenlinks'], {'meta': '1'}) self.api.retried_PUT(url, ET.tostring(flink))
Example #27
Source File: freeze_command.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def create_bootstrap_aggregate_meta(self): url = self.api.makeurl(['source', self.prj, 'bootstrap-copy', '_meta']) root = ET.Element('package', {'project': self.prj, 'name': 'bootstrap-copy'}) ET.SubElement(root, 'title') ET.SubElement(root, 'description') f = ET.SubElement(root, 'build') # this one is to toggle ET.SubElement(f, 'disable', {'repository': 'bootstrap_copy'}) # this one is the global toggle ET.SubElement(f, 'disable') self.api.retried_PUT(url, ET.tostring(root))
Example #28
Source File: GXXmlReader.py From Gurux.DLMS.Python with GNU General Public License v2.0 | 5 votes |
def isStartElement(self, name=None, getNext=False): if name is None: ret = isinstance(self.currentElement, (ET.Element,)) else: ret = isinstance(self.currentElement, (ET.Element,)) and self.currentElement.tag == name if ret and getNext: self.getNext() return ret
Example #29
Source File: core.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def create_change_devel_request(apiurl, source_project, source_package, target_project, target_package=None, message=None): if not message: message = message_suffix('created') request = ETL.Element('request') state = ETL.Element('state') state.set('name', 'new') request.append(state) description = ETL.Element('description') description.text = message request.append(description) action = ETL.Element('action') action.set('type', 'change_devel') request.append(action) source = ETL.Element('source') source.set('project', source_project) source.set('package', source_package) action.append(source) target = ETL.Element('target') target.set('project', target_project) target.set('package', target_package) action.append(target) url = makeurl(apiurl, ['request'], {'cmd': 'create'}) root = ETL.parse(http_POST(url, data=ETL.tostring(request))).getroot() return root.get('id')
Example #30
Source File: core.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def create_delete_request(apiurl, target_project, target_package=None, message=None): if not message: message = message_suffix('created') request = ETL.Element('request') state = ETL.Element('state') state.set('name', 'new') request.append(state) description = ETL.Element('description') description.text = message request.append(description) action = ETL.Element('action') action.set('type', 'delete') request.append(action) target = ETL.Element('target') target.set('project', target_project) if target_package: target.set('package', target_package) action.append(target) url = makeurl(apiurl, ['request'], {'cmd': 'create'}) root = ETL.parse(http_POST(url, data=ETL.tostring(request))).getroot() return root.get('id') # Should exist within osc.core like create_submit_request(), but rather it was # duplicated in osc.commandline.