Python xml.etree.ElementTree.SubElement() Examples

The following are 30 code examples of xml.etree.ElementTree.SubElement(). 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: xmls.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def tvtunes_nfo(path, urls):

    ''' Create tvtunes.nfo
    '''
    try:
        xml = etree.parse(path).getroot()
    except Exception:
        xml = etree.Element('tvtunes')

    for elem in xml.getiterator('tvtunes'):
        for file in list(elem):
            elem.remove(file)

    for url in urls:
        etree.SubElement(xml, 'file').text = url

    indent(xml)
    write_xml(etree.tostring(xml, 'UTF-8'), path) 
Example #2
Source File: userid.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def logouts(self, users):
        """Logout multiple users in the same API call

        This method can be batched with batch_start() and batch_end().

        Arguments:
            users: a list of sets of user/ip mappings
                   eg. [(user1, 10.0.1.1), (user2, 10.0.1.2)]

        """
        if not users:
            return
        root, payload = self._create_uidmessage()
        logout = payload.find("logout")
        if logout is None:
            logout = ET.SubElement(payload, "logout")
        for user in users:
            ET.SubElement(logout, "entry", {"name": user[0], "ip": user[1]})
        self.send(root) 
Example #3
Source File: userid.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def logout(self, user, ip):
        """Logout a single user

        Removes a mapping of a user to an IP address

        This method can be batched with batch_start() and batch_end().

        Args:
            user (str): a username
            ip (str): an ip address

        """
        root, payload = self._create_uidmessage()
        logout = payload.find("logout")
        if logout is None:
            logout = ET.SubElement(payload, "logout")
        ET.SubElement(logout, "entry", {"name": user, "ip": ip})
        self.send(root) 
Example #4
Source File: userid.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def login(self, user, ip):
        """Login a single user

        Maps a user to an IP address

        This method can be batched with batch_start() and batch_end().

        Args:
            user (str): a username
            ip (str): an ip address

        """
        root, payload = self._create_uidmessage()
        login = payload.find("login")
        if login is None:
            login = ET.SubElement(payload, "login")
        ET.SubElement(login, "entry", {"name": user, "ip": ip})
        self.send(root) 
Example #5
Source File: base.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def remove_config_lock(self, scope="shared", exceptions=True, retry_on_peer=True):
        self._logger.debug("%s: Remove config lock requested for scope %s" % (self.id, scope))
        cmd = ET.Element("request")
        subel = ET.SubElement(cmd, "config-lock")
        subel = ET.SubElement(subel, "remove")
        try:
            self.xapi.op(ET.tostring(cmd, encoding='utf-8'), vsys=scope, retry_on_peer=retry_on_peer)
        except (pan.xapi.PanXapiError, err.PanDeviceXapiError) as e:
            if not re.match(r"Config is not currently locked for scope (shared|vsys\d)", str(e)):
                raise
            else:
                if exceptions:
                    raise err.PanLockError(str(e), pan_device=self)
                else:
                    self._logger.debug(str(e))
                    return False
        self.config_locked = False
        return True 
Example #6
Source File: firewall.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def element(self):
        if self.serial is None:
            raise ValueError("Serial number must be set to generate element")
        entry = ET.Element("entry", {"name": self.serial})
        if self.parent == self.panorama() and self.serial is not None:
            # This is a firewall under a panorama
            if not self.multi_vsys:
                vsys = ET.SubElement(entry, "vsys")
                ET.SubElement(vsys, "entry", {"name": "vsys1"})
        elif self.parent == self.devicegroup() and self.multi_vsys:
            # This is a firewall under a device group
            if self.vsys.startswith("vsys"):
                vsys = ET.SubElement(entry, "vsys")
                ET.SubElement(vsys, "entry", {"name": self.vsys})
            else:
                vsys = ET.SubElement(entry, "vsys")
                all_vsys = self.findall(device.Vsys)
                for a_vsys in all_vsys:
                    ET.SubElement(vsys, "entry", {"name": a_vsys})
        return entry 
Example #7
Source File: __init__.py    From keras2pmml with MIT License 6 votes vote down vote up
def _generate_data_dictionary(root, feature_names, target_name, target_values):
    data_dict = ET.SubElement(root, 'DataDictionary')
    data_field = ET.SubElement(data_dict, 'DataField')
    data_field.set('name', target_name)
    data_field.set('dataType', 'string')
    data_field.set('optype', 'categorical')
    print('[x] Generating Data Dictionary:')
    for t in target_values:
        value = ET.SubElement(data_field, 'Value')
        value.set('value', t)
    for f in feature_names:
        data_field = ET.SubElement(data_dict, 'DataField')
        data_field.set('name', f)
        data_field.set('dataType', 'double')
        data_field.set('optype', 'continuous')
        print('\t[-] {}...OK!'.format(f))
    return data_dict 
Example #8
Source File: base.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def add_config_lock(self, comment=None, scope="shared", exceptions=True, retry_on_peer=True):
        self._logger.debug("%s: Add config lock requested for scope %s" % (self.id, scope))
        cmd = ET.Element("request")
        subel = ET.SubElement(cmd, "config-lock")
        subel = ET.SubElement(subel, "add")
        if comment is not None:
            subel = ET.SubElement(subel, "comment")
            subel.text = comment
        try:
            self.xapi.op(ET.tostring(cmd, encoding='utf-8'), vsys=scope, retry_on_peer=retry_on_peer)
        except (pan.xapi.PanXapiError, err.PanDeviceXapiError) as e:
            if not re.match(r"Config for scope (shared|vsys\d) is currently locked", str(e)) and \
                    not re.match(r"You already own a config lock for scope", str(e)):
                raise
            else:
                if exceptions:
                    raise err.PanLockError(str(e), pan_device=self)
                else:
                    self._logger.debug(str(e))
                    return False
        self.config_locked = True
        return True 
Example #9
Source File: base.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def _perform_vsys_dict_import_set(self, dev, vsys_dict):
        """Iterates of a vsys_dict, doing imports for all instances."""
        for vsys, vsys_spec in vsys_dict.items():
            if vsys is None:
                continue
            for xpath_import_base, objs in vsys_spec.items():
                xpath_tokens = xpath_import_base.split('/')
                new_root = xpath_tokens.pop()

                # Form the xpath from what remains of the xpath.
                xpath = '/'.join(xpath_tokens)

                # Append objects as members to the new root.
                shared_root = ET.Element(new_root)
                for x in objs:
                    ET.SubElement(shared_root, "member").text = x.uid

                # Perform the import.
                dev.xapi.set(xpath, ET.tostring(shared_root, encoding='utf-8'),
                             retry_on_peer=self.HA_SYNC) 
Example #10
Source File: base.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def add_commit_lock(self, comment=None, scope="shared", exceptions=True, retry_on_peer=True):
        self._logger.debug("%s: Add commit lock requested for scope %s" % (self.id, scope))
        cmd = ET.Element("request")
        subel = ET.SubElement(cmd, "commit-lock")
        subel = ET.SubElement(subel, "add")
        if comment is not None:
            subel = ET.SubElement(subel, "comment")
            subel.text = comment
        try:
            self.xapi.op(ET.tostring(cmd, encoding='utf-8'), vsys=scope, retry_on_peer=retry_on_peer)
        except (pan.xapi.PanXapiError, err.PanDeviceXapiError) as e:
            if not re.match(r"Commit lock is already held", str(e)):
                raise
            else:
                if exceptions:
                    raise err.PanLockError(str(e), pan_device=self)
                else:
                    self._logger.debug(str(e))
                    return False
        self.commit_locked = True
        return True 
Example #11
Source File: base.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def _subelements(self, comparable=False):
        """Generator function to turn children into XML objects.

        Yields:
            xml.etree.ElementTree: The next child as an ``ElementTree`` object.

        """
        for child in self.children:
            root = self._root_element()
            # Paths have a leading slash to get rid of
            xpath_sections = child.XPATH.split('/')[1:]
            if child.SUFFIX is None:
                # If not suffix, remove the last xpath section
                # because it will be part of the element
                xpath_sections = xpath_sections[:-1]
            e = root
            for path in xpath_sections:
                e = ET.SubElement(e, path)
            e.append(child.element(comparable=comparable))
            yield root 
Example #12
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def node_inprogressepisodes(self, root):

        for rule in root.findall('.//limit'):
            rule.text = str(self.limit)
            break
        else:
            etree.SubElement(root, 'limit').text = str(self.limit)

        for rule in root.findall('.//rule'):
            if rule.attrib['field'] == 'inprogress':
                break
        else:
            etree.SubElement(root, 'rule', {'field': "inprogress", 'operator':"true"})

        content = root.find('content')
        content.text = "episodes" 
Example #13
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def node_recentepisodes(self, root):

        for rule in root.findall('.//order'):
            if rule.text == "dateadded":
                break
        else:
            etree.SubElement(root, 'order', {'direction': "descending"}).text = "dateadded"

        for rule in root.findall('.//limit'):
            rule.text = str(self.limit)
            break
        else:
            etree.SubElement(root, 'limit').text = str(self.limit)

        for rule in root.findall('.//rule'):
            if rule.attrib['field'] == 'playcount':
                rule.find('value').text = "0"
                break
        else:
            rule = etree.SubElement(root, 'rule', {'field': "playcount", 'operator': "is"})
            etree.SubElement(rule, 'value').text = "0"

        content = root.find('content')
        content.text = "episodes" 
Example #14
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def node_recent(self, root):

        for rule in root.findall('.//order'):
            if rule.text == "dateadded":
                break
        else:
            etree.SubElement(root, 'order', {'direction': "descending"}).text = "dateadded"

        for rule in root.findall('.//limit'):
            rule.text = str(self.limit)
            break
        else:
            etree.SubElement(root, 'limit').text = str(self.limit)

        for rule in root.findall('.//rule'):
            if rule.attrib['field'] == 'playcount':
                rule.find('value').text = "0"
                break
        else:
            rule = etree.SubElement(root, 'rule', {'field': "playcount", 'operator': "is"})
            etree.SubElement(rule, 'value').text = "0" 
Example #15
Source File: xmpp_request_handler.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def _generate_chat(self, to, from_, body):
    data = _FormData()
    data.add_text('from', from_, 'plain')
    data.add_text('to', to, 'plain')
    data.add_text('body', body, 'plain')

    message_element = ElementTree.Element(
        ElementTree.QName('jabber:client', 'message'),
        {'from': from_, 'to': to, 'type': 'chat'})
    body_element = ElementTree.SubElement(
        message_element,
        ElementTree.QName('jabber:client', 'body'))
    body_element.text = body

    data.add_text('stanza',
                  ElementTree.tostring(message_element, encoding='utf-8'),
                  'xml')
    return data 
Example #16
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def node_recommended(self, root):

        for rule in root.findall('.//order'):
            if rule.text == "rating":
                break
        else:
            etree.SubElement(root, 'order', {'direction': "descending"}).text = "rating"

        for rule in root.findall('.//limit'):
            rule.text = str(self.limit)
            break
        else:
            etree.SubElement(root, 'limit').text = str(self.limit)

        for rule in root.findall('.//rule'):
            if rule.attrib['field'] == 'playcount':
                rule.find('value').text = "0"
                break
        else:
            rule = etree.SubElement(root, 'rule', {'field': "playcount", 'operator': "is"})
            etree.SubElement(rule, 'value').text = "0"

        for rule in root.findall('.//rule'):
            if rule.attrib['field'] == 'rating':
                rule.find('value').text = "7"
                break
        else:
            rule = etree.SubElement(root, 'rule', {'field': "rating", 'operator': "greaterthan"})
            etree.SubElement(rule, 'value').text = "7" 
Example #17
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def node_favepisodes(self, root, path):

        for rule in root.findall('.//path'):
            rule.text = path
            break
        else:
            etree.SubElement(root, 'path').text = path

        for rule in root.findall('.//content'):
            rule.text = "episodes"
            break
        else:
            etree.SubElement(root, 'content').text = "episodes" 
Example #18
Source File: userid.py    From terraform-templates with Apache License 2.0 5 votes vote down vote up
def register(self, ip, tags):
        """Register an ip tag for a Dynamic Address Group

        This method can be batched with batch_start() and batch_end().

        Args:
            ip (:obj:`list` or :obj:`str`): IP address(es) to tag
            tags (:obj:`list` or :obj:`str`): The tag(s) for the IP address

        """
        root, payload = self._create_uidmessage()
        register = payload.find("register")
        if register is None:
            register = ET.SubElement(payload, "register")
        ip = list(set(string_or_list(ip)))
        tags = list(set(string_or_list(tags)))
        if not tags:
            return
        tags = [self.prefix+t for t in tags]
        for c_ip in ip:
            tagelement = register.find("./entry[@ip='%s']/tag" % c_ip)
            if tagelement is None:
                entry = ET.SubElement(register, "entry", {"ip": c_ip})
                tagelement = ET.SubElement(entry, "tag")
            for tag in tags:
                member = ET.SubElement(tagelement, "member")
                member.text = tag
        self.send(root) 
Example #19
Source File: base.py    From terraform-templates with Apache License 2.0 5 votes vote down vote up
def _set_inner_xml_tag_text(self, elm, value, comparable=False):
        """Sets the final elm's .text as appropriate given the vartype.

        Args:
            elm (xml.etree.ElementTree.Element): The element whose .text to set.
            value (various): The value to put in the .text, conforming to the vartype of this parameter.
            comparable (bool): Make updates for element string comparisons.  For entry and member vartypes, sort the entries (True) or leave them as-is (False).

        """
        # Create an element containing the value in the instance variable
        if self.vartype == "member":
            values = pandevice.string_or_list(value)
            if comparable:
                values = sorted(values)
            for member in values:
                ET.SubElement(elm, 'member').text = str(member)
        elif self.vartype == "entry":
            values = pandevice.string_or_list(value)
            if comparable:
                values = sorted(values)
            for entry in values:
                ET.SubElement(elm, 'entry', {'name': str(entry)})
        elif self.vartype == "exist":
            if value:
                ET.SubElement(elm, self.variable)
        elif self.vartype == "bool":
            elm.text = yesno(value)
        elif self.path.find("|") != -1:
            # This is an element variable,
            # it has already been created
            # so do nothing
            pass
        elif self.vartype == "none":
            # There is no variable, so don't try to populate it
            pass
        else:
            elm.text = str(value) 
Example #20
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def node_years(self, root):

        for rule in root.findall('.//order'):
            if rule.text == "title":
                break
        else:
            etree.SubElement(root, 'order', {'direction': "descending"}).text = "title"

        for rule in root.findall('.//group'):
            rule.text = "years"
            break
        else:
            etree.SubElement(root, 'group').text = "years" 
Example #21
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def node_nextepisodes(self, root, path):

        for rule in root.findall('.//path'):
            rule.text = path
            break
        else:
            etree.SubElement(root, 'path').text = path

        for rule in root.findall('.//content'):
            rule.text = "episodes"
            break
        else:
            etree.SubElement(root, 'content').text = "episodes" 
Example #22
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def node_all(self, root):

        for rule in root.findall('.//order'):
            if rule.text == "sorttitle":
                break
        else:
            etree.SubElement(root, 'order', {'direction': "ascending"}).text = "sorttitle" 
Example #23
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def add_dynamic_node(self, index, file, view, node, name, path):

        try:
            xml = etree.parse(file).getroot()
        except Exception:
            xml = self.node_root('folder', index)
            etree.SubElement(xml, 'label')
            etree.SubElement(xml, 'content')

        label = xml.find('label')
        label.text = name

        getattr(self, 'node_' + node)(xml, path)
        indent(xml)
        write_xml(etree.tostring(xml, 'UTF-8'), file) 
Example #24
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def add_node(self, index, file, view, node, name):

        try:
            xml = etree.parse(file).getroot()
        except Exception:
            xml = self.node_root('filter', index)
            etree.SubElement(xml, 'label')
            etree.SubElement(xml, 'match')
            etree.SubElement(xml, 'content')


        label = xml.find('label')
        label.text = str(name) if type(name) == int else name

        content = xml.find('content')
        content.text = view['Media']

        match = xml.find('match')
        match.text = "all"

        for rule in xml.findall('.//value'):
            if rule.text == view['Tag']:
                break
        else:
            rule = etree.SubElement(xml, 'rule', {'field': "tag", 'operator': "is"})
            etree.SubElement(rule, 'value').text = view['Tag']

        getattr(self, 'node_' + node)(xml) # get node function based on node type
        indent(xml)
        write_xml(etree.tostring(xml, 'UTF-8'), file) 
Example #25
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def node_root(self, root, index):

        ''' Create the root element
        '''
        if root == 'main':
            element = etree.Element('node', {'order': str(index)})
        elif root == 'filter':
            element = etree.Element('node', {'order': str(index), 'type': "filter"})
        else:
            element = etree.Element('node', {'order': str(index), 'type': "folder"})

        etree.SubElement(element, 'icon').text = "special://home/addons/plugin.video.emby/icon.png"

        return element 
Example #26
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def add_single_node(self, path, index, item_type, view):

        file = os.path.join(path, "emby_%s.xml" % view['Tag'].replace(" ", ""))

        try:
            xml = etree.parse(file).getroot()
        except Exception:
            xml = self.node_root('folder' if item_type == 'favorites' and view['Media'] == 'episodes' else 'filter', index)
            etree.SubElement(xml, 'label')
            etree.SubElement(xml, 'match')
            etree.SubElement(xml, 'content')

        label = xml.find('label')
        label.text = view['Name']

        content = xml.find('content')
        content.text = view['Media']

        match = xml.find('match')
        match.text = "all"

        if view['Media'] != 'episodes':

            for rule in xml.findall('.//value'):
                if rule.text == view['Tag']:
                    break
            else:
                rule = etree.SubElement(xml, 'rule', {'field': "tag", 'operator': "is"})
                etree.SubElement(rule, 'value').text = view['Tag']

        if item_type == 'favorites' and view['Media'] == 'episodes':
            path = self.window_browse(view, 'FavEpisodes')
            self.node_favepisodes(xml, path)
        else:
            self.node_all(xml)

        indent(xml)
        write_xml(etree.tostring(xml, 'UTF-8'), file) 
Example #27
Source File: views.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def add_playlist(self, path, view, mixed=False):

        ''' Create or update the xps file.
        '''
        file = os.path.join(path, "emby%s%s.xsp" % (view['Media'], view['Id']))

        try:
            xml = etree.parse(file).getroot()
        except Exception:
            xml = etree.Element('smartplaylist', {'type': view['Media']})
            etree.SubElement(xml, 'name')
            etree.SubElement(xml, 'match')

        name = xml.find('name')
        name.text = view['Name'] if not mixed else "%s (%s)" % (view['Name'], view['Media'])

        match = xml.find('match')
        match.text = "all"

        for rule in xml.findall('.//value'):
            if rule.text == view['Tag']:
                break
        else:
            rule = etree.SubElement(xml, 'rule', {'field': "tag", 'operator': "is"})
            etree.SubElement(rule, 'value').text = view['Tag']

        indent(xml)
        write_xml(etree.tostring(xml, 'UTF-8'), file) 
Example #28
Source File: xer.py    From asn1tools with MIT License 5 votes vote down vote up
def encode(self, data):
        element = ElementTree.Element(self.name)
        ElementTree.SubElement(element, 'true' if data else 'false')

        return element 
Example #29
Source File: search.py    From watchdog with Apache License 2.0 5 votes vote down vote up
def printCVE_xml(item):
    c = SubElement(r, 'id')
    c.text = item['id']
    c = SubElement(r, 'Published')
    c.text = str(item['Published'])
    c = SubElement(r, 'cvss')
    c.text = str(item['cvss'])
    c = SubElement(r, 'summary')
    c.text = SaxEscape(item['summary'])
    for e in item['references']:
        c = SubElement(r, 'references')
        c.text = SaxEscape(e)
    ranking=[]    
    for e in item['vulnerable_configuration']:
        c = SubElement(r, 'vulnerable_configuration')
        c.text = SaxEscape(e)
        if rankinglookup:
            rank = cves.getranking(cpeid=e)
            if rank and rank not in ranking:
                    ranking.append(rank)
    if rankinglookup:
        for ra in ranking:
            for e in ra:
                for i in e:
                    c = SubElement(r, i)
                    c.text =str(e[i]) 
Example #30
Source File: tva.py    From movistartv2xmltv with GNU General Public License v2.0 5 votes vote down vote up
def channels2xmltv(self,xmltv,clist):
        for channelid in clist.keys():
            channelName = clist[channelid]["name"]
            channelId = channelid
            channelKey = clist[channelid]["shortname"]
            channelIp = clist[channelid]["address"]
            channelPort = str(clist[channelid]["port"])
            channelLogo = clist[channelid]["logo"]
            cChannel = SubElement(xmltv,'channel',{"id": channelKey })
            cName = SubElement(cChannel, "display-name", {"lang":"es"})
            cicon = SubElement(cChannel, "icon", {"src": channelLogo })
            cName.text = channelName
        return xmltv