How to use the lxml.etree.fromstring 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 Digital-Preservation-Finland / dpres-siptools / tests / scripts / test_compile_structmap_ead.py View on Github external
def test_collect_dao_hrefs():
    """Tests that the function collect_dao_hrefs returns a list with
    hrefs without leading slashes from ead3 test data.
    """
    ead3 = (''
            ''
            ''
            '')
    xml = ET.fromstring(ead3)
    hrefs = compile_structmap.collect_dao_hrefs(xml)
    assert hrefs == ['file1.txt', 'file2.txt']
github ansible-network / yang / lookup_plugins / yang_json2xml.py View on Github external
except SystemExit:
            pass
        finally:
            err = sys.stderr.getvalue()
            if err and 'error' in err.lower():
                if not keep_tmp_files:
                    shutil.rmtree(os.path.realpath(os.path.expanduser(JSON2XML_DIR_PATH)), ignore_errors=True)
                raise AnsibleError('Error while translating to xml: %s' % err)
            sys.argv = saved_arg
            sys.stdout = saved_stdout
            sys.stderr = saved_stderr

        try:
            content = re.sub(r'<\? ?xml .*\? ?>', '', content)
            root = etree.fromstring(content)
        except Exception as e:
            raise AnsibleError('Error while reading xml document: %s' % e)
        finally:
            if not keep_tmp_files:
                shutil.rmtree(os.path.realpath(os.path.expanduser(JSON2XML_DIR_PATH)), ignore_errors=True)
        res.append(etree.tostring(root))

        return res
github Juniper / wistar / common / lib / junosUtils.py View on Github external
def push_config_string(xml_string, ip, pw):
    logger.debug("Pushing new config to " + str(ip))
    logger.debug(xml_string)
    dev = get_device_reference(ip, "root", pw)
    xml_data = etree.fromstring(xml_string)
    push_config_element(xml_data, dev, True)
github ktmeaton / NCBImeta / ncbimeta / NCBImetaUtilities.py View on Github external
# Retry the search with unescaped characters
            xml_root_string_orig = etree.tostring(xml_root)
            open_char = "<"
            close_char = ">"
            xml_root_string = (
                str(xml_root_string_orig)
                .replace(open_char, "<")
                .replace(close_char, ">")
                .strip()
            )
            xml_root_string = str(xml_root_string).replace("\\n", "")
            xml_root_string = xml_root_string.replace("\\t", "")
            # Strip off the first 2 char (b') and the final char '
            # print(xml_root_string)
            try:
                xml_root = etree.fromstring(xml_root_string[2:-1])
            # Too aggressive, greater than/less than signs got replaced
            except etree.XMLSyntaxError:
                xml_root_string = (
                    str(xml_root_string_orig).replace("\\n", "").replace("\\t", "")
                )
                xml_root = etree.fromstring(xml_root_string[2:-1])
            # Now retry the search with the tags fixed up
            search_results = xml_root.findall(tag_xpath)
            # If attributes of interest are present and matching

        # --- See if the info we want exists here as attribute values---#
        try:
            if xml_root.get(current_tag) == next_tag:
                xml_dict[column_name].append(xml_root.text)
        except AttributeError:
            pass
github scrapy / parsel / parsel / selector.py View on Github external
def create_root_node(text, parser_cls, base_url=None):
    """Create root node for text using given parser class.
    """
    body = text.strip().replace('\x00', '').encode('utf8') or b''
    parser = parser_cls(recover=True, encoding='utf8')
    root = etree.fromstring(body, parser=parser, base_url=base_url)
    if root is None:
        root = etree.fromstring(b'', parser=parser, base_url=base_url)
    return root
github ties / compal_CH7465LG_py / compal / __init__.py View on Github external
def backup(self, filename=None):
        """
        Backup the configuration and return it's content
        """
        res = self.modem.xml_getter(Get.GLOBALSETTINGS, {})
        xml = etree.fromstring(res.content, parser=self.parser)

        if not filename:
            fname = xml.find('ConfigVenderModel').text + "-Cfg.bin"
        else:
            fname = filename

        res = self.modem.get("/xml/getter.xml", params={'filename': fname},
                             allow_redirects=False)
        if res.status_code != 200:
            LOGGER.error("Did not get configfile response!"
                         " Wrong config file name?")
            return None

        return res.content
github MirakelX / mirakel-android / fixTranslation.py View on Github external
#!/usr/bin/python2.7
import re
import fileinput
import sys
import lxml.etree as et
fin = sys.stdin.read()
parser = et.XMLParser(strip_cdata=False,remove_comments=False)
doc = et.fromstring(fin, parser)

escapeR = re.compile(ur'([^\\])((?:\\\\)*)(\')')
for elem in doc.xpath('//string'):
    if elem.text:
        newtext = re.sub(escapeR, r"\1\2\\\3",elem.text)
        if newtext.find("\n") != -1:
            elem.text = et.CDATA(newtext.strip())
        else:
            elem.text = newtext
print """
github kovidgoyal / calibre / src / calibre / ebooks / oeb / parse_utils.py View on Github external
parent = nroot[0]
        for child in list(data.iter()):
            oparent = child.getparent()
            if oparent is not None:
                oparent.remove(child)
            parent.append(child)
        data = nroot

    # Force into the XHTML namespace
    if not namespace(data.tag):
        log.warn('Forcing', filename, 'into XHTML namespace')
        data.attrib['xmlns'] = XHTML_NS
        data = etree.tostring(data, encoding='unicode')

        try:
            data = etree.fromstring(data, parser=parser)
        except:
            data = data.replace(':=', '=').replace(':>', '>')
            data = data.replace('', '')
            try:
                data = etree.fromstring(data, parser=parser)
            except etree.XMLSyntaxError:
                log.warn('Stripping comments from %s'%
                        filename)
                data = re.compile(r'', re.DOTALL).sub('',
                        data)
                data = data.replace(
                    "",
                    '')
                data = data.replace("", '')
                try:
                    data = etree.fromstring(data,
github modoboa / modoboa / modoboa / extensions / stats / graphics.py View on Github external
"""
        result = []
        cmdargs = []
        for curve in self._curves:
            result += [{
                "name": curve.legend, "color": curve.color, "data": []
            }]
            cmdargs += curve.to_rrd_command_args(rrdfile)
        cmd = "rrdtool xport --start %s --end %s " % (str(start), str(end))
        cmd += " ".join(cmdargs)
        if isinstance(cmd, unicode):
            cmd = cmd.encode("utf-8")
        code, output = exec_cmd(cmd)
        if code:
            return []
        tree = etree.fromstring(output)
        for row in tree.xpath('/xport/data/row'):
            timestamp = int(row.find('t').text)
            for vindex, value in enumerate(row.findall('v')):
                if value.text == 'NaN':
                    result[vindex]['data'].append({'x': timestamp, 'y': 0})
                else:
                    result[vindex]['data'].append(
                        {'x': timestamp, 'y': float(value.text)}
                    )
        return result
github odoo / odoo / addons / website_version / models / ir_ui_view.py View on Github external
    @tools.ormcache_context(**dict(accepted_keys=('lang', 'inherit_branding', 'editable', 'translatable', 'website_id', 'version_id')))
    def _read_template(self, cr, uid, view_id, context=None):
        arch = self.read_combined(cr, uid, view_id, fields=['arch'], context=context)['arch']
        arch_tree = etree.fromstring(arch)

        if 'lang' in context:
            arch_tree = self.translate_qweb(cr, uid, view_id, arch_tree, context['lang'], context)

        self.distribute_branding(arch_tree)
        root = etree.Element('templates')
        root.append(arch_tree)
        arch = etree.tostring(root, encoding='utf-8', xml_declaration=True)
        return arch