我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xml.etree.cElementTree.Element()。
def benchmark(self, benchmark_file): xccdftree = ET.Element("Benchmark") xccdftree.set("id", self.product) xccdftree.set("xsi:schemaLocation", self.schema) xccdftree.set("style", self.version.upper()) xccdftree.set("resolved", self.resolved.lower()) xccdftree.set("xml:lang", self.lang) for prefix, uri in xccdf_ns.items(): xccdftree.set("xmlns:" + prefix, uri) status = xccdf_subelement(xccdftree, "status", benchmark_file, "status", attrib={"date": datestamp}) common_content = common_xccdf_content(xccdftree, benchmark_file) notice = xccdf_subelement(xccdftree, "notice", benchmark_file, "notice", attrib={"id": benchmark_file["notice"]["id"]}) front_matter = xccdf_subelement(xccdftree, "front-matter", benchmark_file, "front-matter") rear_matter = xccdf_subelement(xccdftree, "rear-matter", benchmark_file, "rear-matter") version = xccdf_subelement(xccdftree, "version", benchmark_file, "version") return xccdftree
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=' '))
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 = ' '))
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 = ' '))
def cve_parse(self): """ Resolve the latest rules,parse new rule from cve.xml :return: None """ cve_file = self.get_cve_file() if not isinstance(cve_file, list): tree = self.parse_xml(cve_file) root = tree.getroot() childs = root.findall('.//%sentry' % self.NS) for child in childs: # child is entry Element cve_id = child.attrib['id'] cve_info = self.cve_info(child) if len(cve_info) != 0: self._result[cve_id] = cve_info else: for filename in cve_file: tree = self.parse_xml(filename) root = tree.getroot() childs = root.findall('.//%sentry' % self.NS) for child in childs: # child is entry Element cve_id = child.attrib['id'] cve_info = self.cve_info(child) if len(cve_info) != 0: self._result[cve_id] = cve_info
def CreateEnumDataItem(self, node, data): """ ?????? """ ed_ns = data.item_ns ctx = data.item_val ed_type, ed_desc, ed_items = ctx[:3] ed_id = "%s.%s" %(ed_ns, ed_type) tnode = xmllib.Element("Type", {"Id": ed_id,"Name":ed_type, "Uuid": self.GetTypeUuid(ed_type, ed_ns), "xsi:type":"Types:Enumeration" } ) xmllib.SubElement(tnode, "Description").text = ed_desc #xmllib.SubElement(tnode, "Source").text = "%s[%s]" %(data.source, data.part_name) for item in ed_items: it_name, it_value, it_desc = item[:3] it_id = "%s.%s" %(ed_id, it_name) inode = xmllib.SubElement(tnode, "Literal", {"Id":it_id,"Name":it_name, "Value":str(int( it_value ) ) }) xmllib.SubElement(inode, "Description").text = it_desc node.append(tnode) #cache type node self.datastructs[ed_id] = xmllib.tostring(tnode)
def _build_track_item(track, timeline_range, transition_offsets, br_map): clip_item_e = cElementTree.Element('clipitem', frameBlend='FALSE') _insert_new_sub_element( clip_item_e, 'name', text=os.path.basename(track.name) ) track_e = _build_track(track, timeline_range, br_map) clip_item_e.append(_build_rate(track.source_range.start_time)) clip_item_e.extend([_build_marker(m) for m in track.markers]) clip_item_e.append(track_e) timecode = otio.opentime.RationalTime(0, timeline_range.start_time.rate) _build_item_timings( clip_item_e, track, timeline_range, transition_offsets, timecode ) return clip_item_e
def _build_track(stack, timeline_range, br_map): track_e = cElementTree.Element('sequence') _insert_new_sub_element(track_e, 'name', text=stack.name) _insert_new_sub_element( track_e, 'duration', text='{:.0f}'.format(timeline_range.duration.value) ) track_e.append(_build_rate(timeline_range.start_time)) track_rate = timeline_range.start_time.rate media_e = _insert_new_sub_element(track_e, 'media') video_e = _insert_new_sub_element(media_e, 'video') audio_e = _insert_new_sub_element(media_e, 'audio') for track in stack: if track.kind == otio.schema.TrackKind.Video: video_e.append(_build_top_level_track(track, track_rate, br_map)) elif track.kind == otio.schema.TrackKind.Audio: audio_e.append(_build_top_level_track(track, track_rate, br_map)) for marker in stack.markers: track_e.append(_build_marker(marker)) return track_e
def create_xml(self): for i in range(self._hyperparams['num_objects']): xmldir = '/'.join(str.split(self._hyperparams['filename'], '/')[:-1]) mass = np.random.uniform(.01, 1.) root = ET.Element("top") ET.SubElement(root, "inertial", pos="0 0 0", mass="{}".format(mass), diaginertia="{0} {1} {2}".format(mass/2., mass/2., mass/2.)) tree = ET.ElementTree(root) xml_str = minidom.parseString(ET.tostring( tree.getroot(), 'utf-8')).toprettyxml(indent=" ") xml_str = xml_str.splitlines()[1:] xml_str = "\n".join(xml_str) with open(xmldir+"/mass{}.xml".format(i), "wb") as f: f.write(xml_str)
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=' '))
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()
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 = ' '))
def validated_element(x, tags=None, attrs=None): """Checks if the root element of an XML document or Element meets the supplied criteria. *tags* if specified is either a single allowable tag name or sequence of allowable alternatives *attrs* if specified is a sequence of required attributes, each of which may be a sequence of several allowable alternatives Raises :exc:`XMLError` if the requirements are not met. """ ele = to_ele(x) if tags: if isinstance(tags, basestring): tags = [tags] if ele.tag not in tags: raise XMLError("Element [%s] does not meet requirement" % ele.tag) if attrs: for req in attrs: if isinstance(req, basestring): req = [req] for alt in req: if alt in ele.attrib: break else: raise XMLError("Element [%s] does not have required attributes" % ele.tag) return ele
def _harvest_tree(self, tree, version=1): """Populates object members from the data in the tree Element.""" qname, elements, attributes = self.__class__._get_rules(version) for element in tree: if elements and element.tag in elements: definition = elements[element.tag] # If this is a repeating element, make sure the member is set to a # list. if definition[2]: if getattr(self, definition[0]) is None: setattr(self, definition[0], []) getattr(self, definition[0]).append(_xml_element_from_tree(element, definition[1])) else: setattr(self, definition[0], _xml_element_from_tree(element, definition[1])) else: self._other_elements.append(_xml_element_from_tree(element, XmlElement)) for attrib, value in tree.attrib.iteritems(): if attributes and attrib in attributes: setattr(self, attributes[attrib], value) else: self._other_attributes[attrib] = value if tree.text: self.text = tree.text
def toXML(self, name): sketch = ET.Element("sketch") sketch.attrib["id"] = str(self.sketch_id) for stk in self.strokes: for pnt in stk.points: ET.SubElement(sketch, "point", id = str(pnt.pid), time = str(pnt.time), x = str(pnt.x), y = str(pnt.y)) for stk in self.strokes: stroke = ET.SubElement(sketch, "stroke") stroke.attrib["id"] = str(stk.sid) stroke.attrib["visible"] = "true" for pnt in stk.points: ET.SubElement(stroke, "arg", type = "point").text = str(pnt.pid) tree = ET.ElementTree(sketch) tree.write( os.path.join(os.getcwd(), 'XMLfiles', 'AfterTraining' , str(name) + ".xml") ) # resamples the sketch before IDM feature extraction
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 ####################################################################
def tree_from_html(htmldata, enc='utf-8'): # type: (str, str) -> ETree.Element text = htmldata text = escape_illegal_xmlchars(text) if NARROW_BUILD: # Remove lonely surrogate halfs text = u''.join(iterchars(text)) text = re.sub(' xmlns="[^"]+"', '', text, count=1) text = text.replace(' ', ' ') btext = bytestr('<?xml version="1.0" encoding="%s"?>\n' % enc) + surrencode(text, enc) tree = ETree.fromstring(btext) return tree # The LINENRSEP must not be anything that appears in the line number column of the HTML # generated by difflib which are digits and the line continuation character '>'.
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
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
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: ET.SubElement(event, "done") stream.write(ET.tostring(event)) stream.flush()
def __init__(self): self.item_processor = ItemProcessor() self.root = ET.Element(u'??????????????????????') self.root.set(u'???????????', '2.05') self.root.set(u'????????????????', six.text_type(datetime.now().date()))
def xccdf_element(xccdf_element, yamlcontent, yaml_key=None, attrib=None): yaml_key = yaml_key_value(yamlcontent, yaml_key) new_element = ET.Element(xccdf_element) if attrib is not None: new_element = add_attrib_to_element(new_element, attrib, yamlcontent) return new_element
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 = 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 += [bndbox] # [xmin, ymin, xmax, ymax, label_ind] # img_id = target.find('filename').text[:-4] return res # [[xmin, ymin, xmax, ymax, label_ind], ... ]
def _BecomeChildElement(self, tree): """ Note: Only for use with classes that have a _tag and _namespace class member. It is in AtomBase so that it can be inherited but it should not be called on instances of AtomBase. """ new_child = ElementTree.Element('') tree.append(new_child) new_child.tag = '{%s}%s' % (self.__class__._namespace, self.__class__._tag) self._AddMembersToElementTree(new_child)
def _ToElementTree(self): """ Note, this method is designed to be used only with classes that have a _tag and _namespace. It is placed in AtomBase for inheritance but should not be called on this class. """ new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace, self.__class__._tag)) self._AddMembersToElementTree(new_tree) return new_tree
def ToString(self): element_tree = self._TransferToElementTree(ElementTree.Element('')) return ElementTree.tostring(element_tree, encoding="UTF-8")
def _BecomeChildElement(self, element_tree): """Converts this object into an etree element and adds it as a child node. Adds self to the ElementTree. This method is required to avoid verbose XML which constantly redefines the namespace. Args: element_tree: ElementTree._Element The element to which this object's XML will be added. """ new_element = ElementTree.Element('') element_tree.append(new_element) self._TransferToElementTree(new_element)
def _harvest_tree(self, tree, version=1): """Populates object members from the data in the tree Element.""" qname, elements, attributes = self.__class__._get_rules(version) for element in tree: if elements and element.tag in elements: definition = elements[element.tag] # If this is a repeating element, make sure the member is set to a # list. if definition[2]: if getattr(self, definition[0]) is None: setattr(self, definition[0], []) getattr(self, definition[0]).append(_xml_element_from_tree(element, definition[1], version)) else: setattr(self, definition[0], _xml_element_from_tree(element, definition[1], version)) else: self._other_elements.append(_xml_element_from_tree(element, XmlElement, version)) for attrib, value in tree.attrib.iteritems(): if attributes and attrib in attributes: setattr(self, attributes[attrib], value) else: self._other_attributes[attrib] = value if tree.text: self.text = tree.text
def _become_child(self, tree, version=1): """Adds a child element to tree with the XML data in self.""" new_child = ElementTree.Element('') tree.append(new_child) new_child.tag = _get_qname(self, version) self._attach_members(new_child, version)
def internal_to_elem(pfsh, factory=ET.Element): """Convert an internal dictionary (not JSON!) into an Element. Whatever Element implementation we could import will be used by default; if you want to use something else, pass the Element class as the factory parameter. """ attribs = {} text = None tail = None sublist = [] tag = list(pfsh.keys()) if len(tag) != 1: raise ValueError("Illegal structure with multiple tags: %s" % tag) tag = tag[0] value = pfsh[tag] if isinstance(value, dict): for k, v in list(value.items()): if k[:1] == "@": attribs[k[1:]] = v elif k == "#text": text = v elif k == "#tail": tail = v elif isinstance(v, list): for v2 in v: sublist.append(internal_to_elem({k: v2}, factory=factory)) else: sublist.append(internal_to_elem({k: v}, factory=factory)) else: text = value e = factory(tag, attribs) for sub in sublist: e.append(sub) e.text = text e.tail = tail return e
def elem2json(elem, strip_ns=1, strip=1): """Convert an ElementTree or Element into a JSON string.""" if hasattr(elem, 'getroot'): elem = elem.getroot() return elem_to_internal(elem, strip_ns=strip_ns, strip=strip)
def json2elem(json_data, factory=ET.Element): """Convert a JSON string into an Element. Whatever Element implementation we could import will be used by default; if you want to use something else, pass the Element class as the factory parameter. """ return internal_to_elem(json.loads(json_data), factory)
def json2xml(json_data, factory=ET.Element): """Convert a JSON string into an XML string. Whatever Element implementation we could import will be used by default; if you want to use something else, pass the Element class as the factory parameter. """ if not isinstance(json_data, dict): json_data = json.loads(json_data) elem = internal_to_elem(json_data, factory) return ET.tostring(elem)
def elem_create(self, class_tag, xml_doc=None, override_tag=None): if xml_doc is None: xml_obj = Element(class_tag) else: if override_tag: xml_obj = SubElement(xml_doc, override_tag) else: xml_obj = SubElement(xml_doc, class_tag) return xml_obj
def to_xml(self, xml_doc=None, option=None, cookie=None): """ This method returns the xml element node for the current object with it's hierarchy. Args: xml_doc: document to which the Mo attributes are added. Can be None. option: not required for Generic Mo class object Example: from imcmsdk.imcmo import GenericMo\n args = {"a": 1, "b": 2, "c":3}\n obj = GenericMo("testLsA", "org-root", **args)\n obj1 = GenericMo("testLsB", "org-root", **args)\n obj.add_child(obj1)\n elem = obj.write_xml()\n import imcmsdk.imcxmlcodec as xc\n xc.to_xml_str(elem)\n Output: '<testLsA a="1" b="2" c="3" dn="org-root/" rn="">\n <testLsB a="1" b="2" c="3" dn="org-root/" rn="" />\n </testLsA>' """ if xml_doc is None: xml_obj = Element(imcgenutils.word_l(self._class_id)) else: xml_obj = SubElement(xml_doc, imcgenutils.word_l(self._class_id)) for key in self.__dict__: if not key.startswith('_'): xml_obj.set(key, getattr(self, key)) self.child_to_xml(xml_obj) return xml_obj