How to use the lxml.etree.Element function in lxml

To help you get started, we’ve selected a few lxml examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github intel / test-framework-and-suites-for-android / acs / acs / Core / CampaignGenerator / FailedTestCampaignGenerator.py View on Github external
comment = etree.Comment("This Test Campaign was AUTOMATICALLY" +
                                "generated from input ACS report file: %s" %
                                self.failed_folder_path)
        root.insert(0, comment)
        # remove all test cases
        test_cases = root.findall('TestCases')[0]
        test_cases.clear()
        # replace them with the ones in the Test Report
        children = []
        for element in self.all_tc_name:
            if element not in self.failed_tc_names:
                children.append(
                    etree.Comment(
                        etree.tostring(etree.Element('TestCase', Id=element))))
            else:
                children.append(etree.Element('TestCase', Id=element))
        test_cases.extend(children)
        tree.write(self.output_campaign_name)
        XMLUtil.pretty_print_xml(self.output_campaign_name)
        print "Output Failed Tests Campaign can be found here: ", \
            self.output_campaign_name
github lago-project / lago / lago / providers / libvirt / vm.py View on Github external
interface.append(
                ET.Element(
                    'source',
                    network=self.vm.virt_env.prefixed_name(
                        dev_spec['net'], max_length=15
                    ),
                ),
            )
            interface.append(
                ET.Element(
                    'model',
                    type='virtio',
                ),
            )
            interface.append(
                ET.Element(
                    'driver',
                    name='vhost',
                    queues='2',
                ),
            )
            if self.libvirt_ver > 3001001:
                mtu = dev_spec.get('mtu', '1500')
                if mtu != '1500':
                    interface.append(ET.Element(
                        'mtu',
                        size=str(mtu),
                    ))
            if 'ip' in dev_spec:
                interface.append(
                    ET.Element(
                        'mac', address=utils.ipv4_to_mac(dev_spec['ip'])
github geishatokyo-lightning / lightning / lightning_core / vg / parser.py View on Github external
def get_shapes_as_xml(self):
        shapelist = etree.Element("shapelist")

        for k, v in self.parser.shapes.iteritems():
            shapes = self._make_shape(self.parser.tree, v)

            shapelist.extend(shapes)
            
        return shapelist
github anttisalonen / freekick3 / src / tools / wikifetcher / wikifetcher.py View on Github external
teamnodes = collections.defaultdict(list)

            for in_teamnode in in_teamnodes:
                teamname = in_teamnode.get('name')
                teamname = re.sub(' F\.C\.$', '', teamname)
                teamname = re.sub('^F\.C\. ', '', teamname)
                teamname = shortenName(teamname)
                postext = in_teamnode.get('position')
                if postext:
                    teampos = int(in_teamnode.get('position'))
                else:
                    teampos = 0
                if teampos <= 0:
                    teampos = num_teams / 2
                this_team_strength = topteam_strength - ((topteam_strength - bottomteam_strength) * (teampos / float(num_teams)))
                out_teamnode = etree.Element('Team')
                teamnodes[this_team_strength].append(out_teamnode)
                out_teamnode.set('id', str(self.nextteamid))
                self.nextteamid += 1
                etree.SubElement(out_teamnode, 'Name').text = teamname
                out_playernode = etree.SubElement(out_teamnode, 'Players')

                playerstrengths = PlayerStrengthSetup()
                for in_playernode in in_teamnode.xpath('Player'):
                    # TODO: cut off too many players as appropriate
                    player_name = in_playernode.get('name')
                    player_num  = in_playernode.get('number')
                    player_pos  = in_playernode.get('pos')
                    player_nat  = in_playernode.get('nationality')
                    pc = PlayerConfigurator(shortenName(player_name), player_num, player_pos, player_nat, this_team_strength)
                    pl_strength = playerstrengths.getStrengthCoefficient(pc.pos)
                    playernode = pc.createFreekick3Node(self.nextplayerid, pl_strength)
github NMGRL / pychron / pychron / entry / graphic_generator.py View on Github external
root = Element('root')
    ul = Element('use_label')
    ul.text = 'True' if use_label else 'False'
    root.append(ul)

    outline = Element('outline')
    bb = Element('bounding_box')
    width, height = Element('width'), Element('height')
    width.text, height.text = list(map(str, default_bounds))
    bb.append(width)
    bb.append(height)

    outline.append(bb)
    root.append(outline)

    circles = Element('circles')
    radius = Element('radius')
    radius.text = str(default_radius)
    circles.append(radius)

    face_color = Element('face_color')
    face_color.text = 'white'
    circles.append(face_color)

    root.append(circles)

    i = 0
    off = 0
    reader = csv.reader(open(path, 'r'), delimiter=',')
    # writer = open(path + 'angles.txt', 'w')
    nwriter = None
    if rotate:
github nasa-gibs / onearth / src / scripts / oe_configure_reproject_layer.py View on Github external
ows + 'BoundingBox', crs='urn:ogc:def:crs:EPSG::3857')
            bbox_upper_corner_elem = etree.Element(ows + 'UpperCorner')
            bbox_upper_corner_elem.text = '{0} {1}'.format(
                -dest_top_left_corner[0], -dest_top_left_corner[0])
            bbox_lower_corner_elem = etree.Element(ows + 'LowerCorner')
            bbox_lower_corner_elem.text = '{0} {1}'.format(
                dest_top_left_corner[0], dest_top_left_corner[0])
            bbox_elem.append(bbox_lower_corner_elem)
            bbox_elem.append(bbox_upper_corner_elem)
            layer.insert(bb_elem_idx, bbox_elem)

            # Add the TMSs we are using (clearing the ones from the source GC)
            tms_link_elem = layer.find('{*}TileMatrixSetLink')
            tms_link_elem.clear()
            for tms in out_tilematrixsets:
                tms_elem = etree.Element('TileMatrixSet')
                tms_elem.text = tms.findtext('{*}Identifier')
                tms_link_elem.append(tms_elem)

            # Modify the ResourceURL template
            base_url = wmts_service_url + identifier
            if static:
                wmts_service_template = base_url + \
                    '/default/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}' + \
                    dest_file_ext
            else:
                wmts_service_template = base_url + \
                    '/default/{Time}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}' + dest_file_ext
            dest_resource_url_elem.set('template', wmts_service_template)

            wmts_gc_snippet_filename = '{0}_reproject.xml'.format(identifier)
            try:
github seedoo / old / src / seedoo_protocollo / segnatura / segnatura_xml.py View on Github external
def createAOO(self):
        aOO = etree.Element("AOO")
        denominazione = self.createDenominazione()
        codiceAOO = self.createCodiceAOO()

        aOO.append(denominazione)
        aOO.append(codiceAOO)
        return aOO
github IBM / watson-assistant-workbench / scripts / dialog_xml2json.py View on Github external
def generateRepeatNode(parent, root, output, attempts, varName, varValue, goto):
    # node
    repeatNode = LET.Element('node')
    generateNodeName(repeatNode, 'REPEAT_')
    logger.verbose('Generate repeat node for parent: %s named: %s START', parent.find('name').text if parent is not None else 'root', repeatNode.find('name').text)
    # condition
    repeatNodeCondition = LET.Element('condition')
    repeatNodeCondition.text = ('$' + varName + ' == null or ' if attempts == 0 else '') + '$' + varName + ' >= ' + str(attempts)
    repeatNode.append(repeatNodeCondition)
    # context
    repeatNodeContext = LET.Element('context')
    repeatVariable = LET.Element(varName)
    repeatVariable.text = str(varValue)
    if isinstance(varValue, int):
        repeatVariable.set('type', 'number')
    repeatNodeContext.append(repeatVariable)
    repeatNode.append(repeatNodeContext)
    # output
    repeatNode.append(copy.deepcopy(output))
github ansible / ansible / lib / ansible / modules / network / junos / _junos_interface.py View on Github external
if not admin_status or not conditional(state, admin_status[0].text.strip()):
                failed_conditions.append('state ' + 'eq(%s)' % state)

        if tx_rate:
            output_bps = reply.xpath('interface-information/physical-interface/traffic-statistics/output-bps')
            if not output_bps or not conditional(tx_rate, output_bps[0].text.strip(), cast=int):
                failed_conditions.append('tx_rate ' + tx_rate)

        if rx_rate:
            input_bps = reply.xpath('interface-information/physical-interface/traffic-statistics/input-bps')
            if not input_bps or not conditional(rx_rate, input_bps[0].text.strip(), cast=int):
                failed_conditions.append('rx_rate ' + rx_rate)

        if want_neighbors:
            if neighbors is None:
                element = Element('get-lldp-interface-neighbors')
                intf_name = SubElement(element, 'interface-device')
                intf_name.text = item.get('name')

                reply = exec_rpc(module, tostring(element), ignore_warning=False)
                have_host = [item.text for item in reply.xpath('lldp-neighbors-information/lldp-neighbor-information/lldp-remote-system-name')]
                have_port = [item.text for item in reply.xpath('lldp-neighbors-information/lldp-neighbor-information/lldp-remote-port-id')]

            for neighbor in want_neighbors:
                host = neighbor.get('host')
                port = neighbor.get('port')
                if host and host not in have_host:
                    failed_conditions.append('host ' + host)
                if port and port not in have_port:
                    failed_conditions.append('port ' + port)
    if failed_conditions:
        msg = 'One or more conditional statements have not been satisfied'
github AnoopAlias / AUTOM8N / scripts / generate_config.py View on Github external
"""Add a vhost to resin and restart railo-resin app server"""
    resin_conf_dir = "/var/resin/hosts/"
    if not os.path.exists(document_root+"/WEB-INF"):
        os.mkdir(document_root+"/WEB-INF", 0o770)
    if not os.path.exists(document_root+"/log"):
        os.mkdir(document_root+"/log", 0o770)
    uid_user = pwd.getpwnam(user_name).pw_uid
    uid_nobody = pwd.getpwnam("nobody").pw_uid
    gid_nobody = grp.getgrnam("nobody").gr_gid
    os.chown(document_root+"/WEB-INF", uid_user, gid_nobody)
    os.chown(document_root+"/log", uid_user, gid_nobody)
    os.chmod(document_root+"/WEB-INF", 0o770)
    os.chmod(document_root+"/log", 0o770)
    nsm = {None: "http://caucho.com/ns/resin"}
    mydict = {'id': "/", 'root-directory': document_root}
    page = etree.Element('host', nsmap=nsm)
    doc = etree.ElementTree(page)
    host_name = etree.SubElement(page, 'host-name')
    host_name.text = domain_name
    for domain in domain_aname_list:
        host_alias = etree.SubElement(page, 'host-alias')
        host_alias.text = domain
    web_app = etree.SubElement(page, 'web-app', mydict)
    if not os.path.exists(resin_conf_dir+domain_name):
        os.mkdir(resin_conf_dir+domain_name, 0o755)
    os.chown(resin_conf_dir+domain_name, uid_nobody, gid_nobody)
    host_xml_file = resin_conf_dir+domain_name+"/host.xml"
    outFile = open(host_xml_file, 'w')
    doc.write(host_xml_file, method='xml', pretty_print=True)
    outFile.close()
    os.chown(host_xml_file, uid_nobody, gid_nobody)
    return