Python xml.etree.ElementTree.Element() Examples

The following are 30 code examples of xml.etree.ElementTree.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.ElementTree , or try the search function .
Example #1
Source File: service_record.py    From bluescan with GNU General Public License v3.0 6 votes vote down vote up
def pp_additional_protocol_descp_lists(self, attr:ElementTree.Element):
        '''Parse and print AdditionalProtocolDescriptorLists (0x000D).
        
        XML example:
    	    <attribute id="0x000d">
                <sequence>
                    <sequence>
                        <sequence>
                            <uuid value="0x0100" />
                            <uint16 value="0x001b" />
                        </sequence>

                        <sequence>
                            <uuid value="0x0017" />
                            <uint16 value="0x0103" />
                        </sequence>
                    </sequence>
                </sequence>
            </attribute>
        '''
        sequences = attr.find('./sequence').findall('./sequence')
        for sequence in sequences:
            pseudo_attr = ElementTree.Element('attribute')
            pseudo_attr.append(sequence)
            self.pp_protocol_descp_list(pseudo_attr) 
Example #2
Source File: pkmixins.py    From pkmeter with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _init(self, etree, control, parent=None):
        self.etree = etree                          # Element tree to parse
        self.control = control                      # Control class (for callback connect)
        self.parent = parent                        # Parent widget
        self.id = None                              # ID of this widget (if specified)
        self.data = utils.Bunch()                   # Metadata to append to object
        self.actions = []                           # List of actions
        self.manifest = utils.Bunch()               # Dict of element ids
        self.bgimage = None                         # Background image
        self.bgpos = (0,0)                          # Background position 'x,y' or 'center,top' etc..
        self.bgsize = 'fit'                         # Background size 'x,y' or 'fit'
        self.bgfade = 0                             # Fade bgimage when changed (0 to disable)
        self.bgopacity = 1.0                        # Current bgopacity (used during transition)
        self.click_enabled = False                  # Set True when click event enabled
        self.dblclick_enabled = False               # Set True when dblclick event enabled
        self.installEventFilter(self)               # Capture events for interactions
        self._init_attributes()                     # Process all attributes (and actions)
        self.children = self._append_children()     # Build all Chiuldren
        if parent is not None:
            parent.layout().addWidget(self) 
Example #3
Source File: toolbox.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def _chunk_parse(self, grammar=None, root_label='record', trace=0, **kwargs):
        """
        Returns an element tree structure corresponding to a toolbox data file
        parsed according to the chunk grammar.

        :type grammar: str
        :param grammar: Contains the chunking rules used to parse the
            database.  See ``chunk.RegExp`` for documentation.
        :type root_label: str
        :param root_label: The node value that should be used for the
            top node of the chunk structure.
        :type trace: int
        :param trace: The level of tracing that should be used when
            parsing a text.  ``0`` will generate no tracing output;
            ``1`` will generate normal tracing output; and ``2`` or
            higher will generate verbose tracing output.
        :type kwargs: dict
        :param kwargs: Keyword arguments passed to ``toolbox.StandardFormat.fields()``
        :rtype: ElementTree._ElementInterface
        """
        from nltk import chunk
        from nltk.tree import Tree

        cp = chunk.RegexpParser(grammar, root_label=root_label, trace=trace)
        db = self.parse(**kwargs)
        tb_etree = Element('toolbox_data')
        header = db.find('header')
        tb_etree.append(header)
        for record in db.findall('record'):
            parsed = cp.parse([(elem.text, elem.tag) for elem in record])
            tb_etree.append(self._tree2etree(parsed))
        return tb_etree 
Example #4
Source File: etree_helpers.py    From django-payfast with MIT License 6 votes vote down vote up
def find_id_maybe(base, id):  # type: (_Element, str) -> Optional[Element]
    """
    Return the child element with the given id, or None.
    """
    assert id.replace('-', '').isalnum(), id
    matches = base.findall('.//*[@id="{}"]'.format(id))
    if 0 == len(matches):
        return None
    elif 1 == len(matches):
        [match] = matches
        return match
    else:
        raise ValueError(
            'Found {} matching elements with id {!r}'.format(len(matches), id),
            matches,
        ) 
Example #5
Source File: objectTracker.py    From python-esppy with Apache License 2.0 6 votes vote down vote up
def _feature_to_element(self):
        e = xml.Element("input");
        e.attrib["count"] = str(self._count)
        e.attrib["score"] = str(self._score)
        e.attrib["label"] = str(self._label)
        e.attrib["coord-type"] = str(self._coordType)
        if self._coordType == "rect" or self._coordType == "yolo":
            e.attrib["x"] = str(self._x)
            e.attrib["y"] = str(self._y)
            e.attrib["width"] = str(self._width)
            e.attrib["height"] = str(self._height)
        elif self._coordType == "coco":
            e.attrib["x-min"] = str(self._xMin)
            e.attrib["y-min"] = str(self._yMin)
            e.attrib["x-max"] = str(self._xMax)
            e.attrib["y-max"] = str(self._yMax)
        return(e) 
Example #6
Source File: service_record.py    From bluescan with GNU General Public License v3.0 6 votes vote down vote up
def pp_browse_group_list(self, attr:ElementTree.Element):
        '''Parse and print BrowseGroupList (0x0005).

        XML example:
            <attribute id="0x0005">
                <sequence>
                    <uuid value="0x1002" />
                </sequence>
            </attribute>
        '''
        sequence = attr.find('./sequence')
        uuids = sequence.findall('./uuid')
        for uuid in uuids:
            uuid  = uuid.attrib['value']
            print('\t'+uuid+':', end=' ')
            
            if uuid == "0x1002":
                print('PublicBrowseRoot')
            else:
                print('Unknown') 
Example #7
Source File: connections.py    From python-esppy with Apache License 2.0 6 votes vote down vote up
def toJson(self):
        e = ElementTree.Element("schema")
        fields = []
        for field in self._fields:
            f = {}
            f["name"] = field["name"]
            f["espType"] = field["espType"]
            f["type"] = field["type"]
            f["isNumber"] = field["isNumber"]
            f["isDate"] = field["isDate"]
            f["isTime"] = field["isTime"]
            if field["isKey"]:
                f["isKey"] = "true"
            else:
                f["isKey"] = "false"
            fields.append(f)
        return(fields) 
Example #8
Source File: mjcf_utils.py    From robosuite with MIT License 6 votes vote down vote up
def new_geom(geom_type, size, pos=(0, 0, 0), rgba=RED, group=0, **kwargs):
    """
    Creates a geom element with attributes specified by @**kwargs.

    Args:
        geom_type (str): type of the geom.
            see all types here: http://mujoco.org/book/modeling.html#geom
        size: geom size parameters.
        pos: 3d position of the geom frame.
        rgba: color and transparency. Defaults to solid red.
        group: the integrer group that the geom belongs to. useful for
            separating visual and physical elements.
    """
    kwargs["type"] = str(geom_type)
    kwargs["size"] = array_to_string(size)
    kwargs["rgba"] = array_to_string(rgba)
    kwargs["group"] = str(group)
    kwargs["pos"] = array_to_string(pos)
    element = ET.Element("geom", attrib=kwargs)
    return element 
Example #9
Source File: wider_voc.py    From hand-detection.PyTorch with MIT License 6 votes vote down vote up
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: xml.py    From python-esppy with Apache License 2.0 6 votes vote down vote up
def ensure_element(data):
    '''
    Ensure the given object is an ElementTree.Element

    Parameters
    ----------
    data : string or Element

    Returns
    -------
    :class:`ElementTree.Element`

    '''
    if isinstance(data, six.string_types):
        return from_xml(data)
    return data 
Example #11
Source File: xml.py    From python-esppy with Apache License 2.0 6 votes vote down vote up
def from_xml(data):
    '''
    Convert XML to ElementTree.Element

    Parameters
    ----------
    data : string
        The XML to parse

    Returns
    -------
    :class:`ElementTree.Element`

    '''
    try:
        return ET.fromstring(data)
    except:
        for i, line in enumerate(data.split('\n')):
            print(i+1, line)
        raise 
Example #12
Source File: objects.py    From robosuite with MIT License 6 votes vote down vote up
def get_collision(self, name=None, site=False):

        collision = copy.deepcopy(self.worldbody.find("./body/body[@name='collision']"))
        collision.attrib.pop("name")
        if name is not None:
            collision.attrib["name"] = name
            geoms = collision.findall("geom")
            if len(geoms) == 1:
                geoms[0].set("name", name)
            else:
                for i in range(len(geoms)):
                    geoms[i].set("name", "{}-{}".format(name, i))
        if site:
            # add a site as well
            template = self.get_site_attrib_template()
            template["rgba"] = "1 0 0 0"
            if name is not None:
                template["name"] = name
            collision.append(ET.Element("site", attrib=template))
        return collision 
Example #13
Source File: objects.py    From robosuite with MIT License 6 votes vote down vote up
def _get_visual(self, name=None, site=False, ob_type="box"):
        main_body = ET.Element("body")
        if name is not None:
            main_body.set("name", name)
        template = self.get_visual_attrib_template()
        template["type"] = ob_type
        template["rgba"] = array_to_string(self.rgba)
        template["size"] = array_to_string(self.size)
        main_body.append(ET.Element("geom", attrib=template))
        if site:
            # add a site as well
            template = self.get_site_attrib_template()
            if name is not None:
                template["name"] = name
            main_body.append(ET.Element("site", attrib=template))
        return main_body 
Example #14
Source File: argument.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 #15
Source File: event.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _to_xml(self):
        _event = ET.Element('event')
        if self._stanza:
            _event.set('stanza', self._stanza)
        if self._unbroken:
            _event.set('unbroken', str(int(self._unbroken)))

        if self._time:
            ET.SubElement(_event, 'time').text = self._time

        sub_elements = [('index', self._index),
                        ('host', self._host),
                        ('source', self._source),
                        ('sourcetype', self._sourcetype)]
        for node, value in sub_elements:
            if value:
                ET.SubElement(_event, node).text = value

        if isinstance(self._data, (unicode, basestring)):
            ET.SubElement(_event, 'data').text = self._data
        else:
            ET.SubElement(_event, 'data').text = json.dumps(self._data)

        if self._done:
            ET.SubElement(_event, 'done')

        return _event 
Example #16
Source File: event.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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")

        if isinstance(stream, TextIOBase):
            stream.write(ensure_text(ET.tostring(event)))
        else:
            stream.write(ET.tostring(event))
        stream.flush() 
Example #17
Source File: scheme.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def to_xml(self):
        """Creates an ``ET.Element`` representing self, then returns it.

        :returns: 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 #18
Source File: event.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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).decode())
        stream.flush() 
Example #19
Source File: scheme.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def to_xml(self):
        """Creates an ``ET.Element`` representing self, then returns it.

        :returns: 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 #20
Source File: event.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
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")

        if isinstance(stream, TextIOBase):
            stream.write(ensure_text(ET.tostring(event)))
        else:
            stream.write(ET.tostring(event))
        stream.flush() 
Example #21
Source File: __init__.py    From keras2pmml with MIT License 5 votes vote down vote up
def keras2pmml(estimator, transformer=None, file=None, **kwargs):
    """
    Exports Keras model as PMML.

    :param estimator: Keras model to be exported as PMML (for supported models - see bellow).
    :param transformer: if provided then scaling is applied to data fields.
    :param file: name of the file where the PMML will be exported.
    :param kwargs: set of params that affects PMML metadata - see documentation for details.
    :return: XML element tree
    """

    feature_names = kwargs.get('feature_names', [])
    target_name = kwargs.get('target_name', 'class')
    target_values = kwargs.get('target_values', [])
    model_name = kwargs.get('model_name', None)

    feature_names, target_values = _validate_inputs(estimator, transformer, feature_names, target_values)

    pmml = ET.Element('PMML')
    pmml.set('version', '4.3')
    pmml.set('xmlns', 'http://www.dmg.org/PMML-4_3')
    _generate_header(pmml, kwargs)
    _generate_data_dictionary(pmml, feature_names, target_name, target_values)
    _generate_neural_network(pmml, estimator, transformer, feature_names, target_name, target_values, model_name)

    tree = ET.ElementTree(pmml)
    print('[x] Generation of PMML successful.')
    if file:
        tree.write(file, encoding='utf-8', xml_declaration=True)
    return tree 
Example #22
Source File: service_record.py    From bluescan with GNU General Public License v3.0 5 votes vote down vote up
def pp_bt_profile_descp_list(self, attr:ElementTree.Element):
        '''Parse and print BluetoothProfileDescriptorList (0x0009).
        
        XML example:
            <attribute id="0x0009">
                <sequence>
                    <sequence>
                        <uuid value="0x1108" />
                        <uint16 value="0x0102" />
                    </sequence>
                </sequence>
            </attribute>
        '''
        sequence = attr.find('./sequence')
        profiles = sequence.findall('./sequence')
        for profile in profiles:
            uuid = profile.find('./uuid').attrib['value']
            print('\t'+uuid+':', end=' ')
            try:
                uuid = int(uuid[2:], base=16)
            except ValueError:
                pass

            try:
                
                if 'Profile' in service_cls_profile_ids[uuid]['Allowed Usage']:
                    name = service_cls_profile_ids[uuid]['Name']
                    print(green(name), end=' ')
                    # print('\t\t', service_cls_profile_ids[uuid]['Specification'])
                else:
                    print(red('Unknown'), end=' ')
                version = int(profile.find('./uint16').attrib['value'][2:], base=16)
                print(green('v%d.%d'%(version>>8, version&0xFF)))
            except KeyError:
                print(red('Unknown')) 
Example #23
Source File: service_record.py    From bluescan with GNU General Public License v3.0 5 votes vote down vote up
def pp_service_cls_list(self, attr:ElementTree.Element):
        '''Parse and print ServiceClassIDList (0x0001).
        
        XML example:
            <attribute id="0x0001">
                <sequence>
                    <uuid value="0x110e" />
                    <uuid value="0x110f" />
                </sequence>
            </attribute>
        '''
        sequence = attr.find('./sequence')
        uuids = sequence.findall('./uuid')
        for uuid in uuids:
            uuid = uuid.attrib['value']
            print('\t'+uuid+':', end=' ')
            try:
                uuid = int(uuid[2:], base=16)
            except ValueError:
                pass

            try:
                if 'Service Class' in service_cls_profile_ids[uuid]['Allowed Usage']:
                    self.service_clses.append(uuid)
                    name = service_cls_profile_ids[uuid]['Name']
                    print(green(name))
                else:
                    print(red('Unknown'))
            except KeyError:
                if uuid == 0x1800:
                    print(green('Generic Access'))
                elif uuid == 0x1801:
                    print(green('Generic Attribute'))
                else:
                    print(red('Unknown')) 
Example #24
Source File: service_record.py    From bluescan with GNU General Public License v3.0 5 votes vote down vote up
def pp_service_record_hdl(self, attr:ElementTree.Element):
        '''Parse and print ServiceRecordHandle (0x0000).
        
        XML example:
            <attribute id="0x0000">
                <uint32 value="0x00010001" />
            </attribute>
        '''
        handle = attr.find('./uint32')
        
        # Value is a attribute of the uint32 element  
        print('\t' + handle.attrib['value']) 
Example #25
Source File: xml.py    From SenseMe with GNU General Public License v3.0 5 votes vote down vote up
def data_to_xml(d, name="data"):
    """Convert data to XML."""
    r = ET.Element(name)
    return ET.tostring(build_xml(r, d)) 
Example #26
Source File: cxml.py    From yang-explorer with Apache License 2.0 5 votes vote down vote up
def make_node(self, name):
        node = ET.Element('node')
        node.set('name', name)
        return node 
Example #27
Source File: cxml.py    From yang-explorer with Apache License 2.0 5 votes vote down vote up
def CDATA(text=None):
    element = ET.Element('![CDATA[')
    element.text = text
    return element 
Example #28
Source File: pyimport.py    From yang-explorer with Apache License 2.0 5 votes vote down vote up
def emit(self, ctx, modules, fd):
        if ctx.opts.tree_path is not None:
            path = string.split(ctx.opts.tree_path, '/')
            if path[0] == '':
                path = path[1:]
        else:
            path = None

        xmodules = ET.Element('modules')
        for module in modules:
            xmodule = self.emit_imports(module)
            if xmodule is not None:
                xmodules.append(xmodule)

        fd.write(ET.tostring(xmodules)) 
Example #29
Source File: workflow.py    From gist-alfred with MIT License 5 votes vote down vote up
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 #30
Source File: workflow.py    From wechat-alfred-workflow with MIT License 5 votes vote down vote up
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
    ####################################################################