How to use the lxml.etree 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 shadow / shadow / src / tools / convert_multi_app.py View on Github external
def main():
    if len(sys.argv) < 3:
        print 'Usage: {0}  '.format(sys.argv[0])
        sys.exit(0)

    # mappings from scallion types to plugins
    scallion_plugins = {'client': 'filetransfer', 'torrent': 'torrent'}

    tree = etree.parse(sys.argv[1])
    root = tree.getroot()

    # create kill element
    kill = root.find('kill')

    # create plugin elements
    plugins = root.iter('plugin')

    # get software elements
    software = {}
    for element in root.iter('software'):
        software[element.attrib['id']] = element

    nodes = []
    for element in root.iter('node'):
        node = etree.Element('node')
github Bcfg2 / bcfg2 / src / lib / Bcfg2 / Server / Admin / Compare.py View on Github external
def compareSpecifications(self, path1, path2):
        try:
            new = lxml.etree.parse(path1).getroot()
        except IOError:
            print("Failed to read %s" % (path1))
            raise SystemExit(1)

        try:
            old = lxml.etree.parse(path2).getroot()
        except IOError:
            print("Failed to read %s" % (path2))
            raise SystemExit(1)

        for src in [new, old]:
            for bundle in src.findall('./Bundle'):
                if bundle.get('name')[-4:] == '.xml':
                    bundle.set('name', bundle.get('name')[:-4])

        identical = True

        for bundle in old.findall('./Bundle'):
            if len(new.xpath('Bundle[@name="%s"]' % (bundle.get('name')))) == 0:
                print(" Bundle %s only in old configuration" %
                      bundle.get('name'))
                identical = False
github Digital-Preservation-Finland / dpres-ipt-deprecated-2019-11-22 / ipt / validator / xmllint.py View on Github external
def construct_xsd(self, document_tree):
        """This method constructs one schema file which collects all used
        schemas from given document tree and imports all of them in one file.


        :tree: XML tree (lxml.etree) where XSD is constructed
        :returns: Path to the constructed XSD schema
        """

        xsd_exists = False

        parser = etree.XMLParser(dtd_validation=False, no_network=True)
        schema_tree = etree.XML(SCHEMA_TEMPLATE, parser)

        schema_locations = set(document_tree.xpath(
            '//*/@xsi:schemaLocation', namespaces={'xsi': XSI}))
        for schema_location in schema_locations:
            xsd_exists = True

            namespaces_locations = schema_location.strip().split()
            # Import all found namspace/schema location pairs
            for namespace, location in zip(*[iter(namespaces_locations)] * 2):
                xs_import = etree.Element(XS + 'import')
                xs_import.attrib['namespace'] = namespace
                xs_import.attrib['schemaLocation'] = location
                schema_tree.append(xs_import)

        schema_locations = set(document_tree.xpath(
github choderalab / ensembler / scripts / attic / retrieve-templates-uniprot.py View on Github external
with open(new_uniprot_xml_path, 'w') as new_uniprot_xml_file:
        new_uniprot_xml_file.write(new_xml + '\n')
    with open('tmp-diff', 'w') as diff_file:
        call(['diff', '--ignore-matching-lines= 0:
        print 'Differences found:\n==========\n'
        print ''.join(diff)
        print '\n==========\n'
    else:
        print '\n==========\nNo differences found. Continuing anyway.\n==========\n'
    print 'Saving new XML document as:', uniprot_xml_path
    os.rename('tmp-new-uniprot.xml', uniprot_xml_path)
    os.remove('tmp-diff')
    uniprot_xml = etree.parse(uniprot_xml_path, parser).getroot()

nuniprot_kinases = len(uniprot_kinases)
print 'Number of entries in UniProt XML document:', nuniprot_kinases

# =================================
# Iterate through the kinases in the downloaded UniProt XML document, and store relevant info (identifiers, pk_domains, pk_pdbs) in XML etree "templates" (note that this XML etree is only used internally, and is not output to file)
# =================================
templates = etree.Element('templates')
template_ids = []
npdb_chains = 0
pdbids = [] # Just used for checking how many PDB and SIFTS XML files will be required
for k in range(nuniprot_kinases):
    AC = uniprot_kinases[k].findtext('accession')
    entry_name = uniprot_kinases[k].findtext('name')
    sequence = ''.join( uniprot_kinases[k].findtext('sequence[@length]').split() )
github fmenabe / python-kvm / kvm / __init__.py View on Github external
def xml_method(self, *args, **kwargs):
        with self._host.set_controls(parse=True, ignore_opts=ignore_opts):
            xml = '\n'.join(self._host.virsh(cmd, *args, **kwargs))
        return from_xml(etree.fromstring(xml), conf.get('lists', []))[conf['key']]
github lkiesow / python-feedgen / feedgen / util.py View on Github external
def xml_fromstring(xmlstring):
    return lxml.etree.fromstring(xmlstring, parser)  # nosec - safe parser
github upgrades-migrations / preupgrade-assistant / preupg / preupg_diff.py View on Github external
def stringify_children(tag_obj):
    """
    Return body of the given node 'tag_obj'. For example, if the node contains
    following text: 'str1<br>str2<b>str3</b>str4'
    then tag_obj.text contains just 'str1' and rest of text is thrown away.
    This function returns whole text inside the given node.
    """
    s = tag_obj.text
    if s is None:
        s = ''
    else:
        s = s.encode("UTF-8")
    for child in tag_obj:
        s += ET.tostring(child, encoding="UTF-8")
    return s
github iocast / featureserver / FeatureServer / Parsers / WFS_V1_Parser.py View on Github external
def parse_filter(self, datasource, dom, properties=[]):
        ''' parses a OGC  tag '''
        return Select(datasource=datasource, data=etree.tostring(dom), properties=properties, service=self.service)
github opacam / Cohen3 / coherence / upnp / core / DIDLLite.py View on Github external
self.artist = child.text
            elif child.tag.endswith('genre'):
                if self.genre is not None:
                    if self.genres is None:
                        self.genres = [self.genre]
                    self.genres.append(child.text)
                self.genre = child.text

            elif child.tag.endswith('album'):
                self.album = child.text
            elif child.tag.endswith('class'):
                self.upnp_class = child.text
            elif child.tag.endswith('server_uuid'):
                self.server_uuid = child.text
            elif child.tag.endswith('res'):
                res = Resource.fromString(etree.tostring(child))
                self.res.append(res)
github driscollis / applications_with_wxpython / chapter13_xml_editor / version_2_working_ui / editor_page.py View on Github external
def parse_xml(self, xml_path):
        """
        Parses the XML from the file that is passed in
        """
        self.current_directory = os.path.dirname(xml_path)
        try:
            self.xml_tree = ET.parse(xml_path)
        except IOError:
            print('Bad file')
            return
        except Exception as e:
            print('Really bad error')
            print(e)
            return

        self.xml_root = self.xml_tree.getroot()