How to use the defusedxml.ElementTree function in defusedxml

To help you get started, we’ve selected a few defusedxml 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 Kozea / CairoSVG / cairosvg / parser.py View on Github external
'No input. Use one of bytestring, file_obj or url.')
        self_is_parent = (
            (parent and self.url == parent.url) or
            (url and url.startswith('#') and not self.url))
        if self_is_parent:
            root_parent = parent
            while root_parent.parent is not None:
                root_parent = root_parent.parent
            tree = root_parent.xml_tree
        else:
            if not bytestring:
                bytestring = self.fetch_url(
                    parse_url(self.url), 'image/svg+xml')
            if len(bytestring) >= 2 and bytestring[:2] == b'\x1f\x8b':
                bytestring = gzip.decompress(bytestring)
            tree = ElementTree.fromstring(
                bytestring, forbid_entities=not unsafe,
                forbid_external=not unsafe)
        self.xml_tree = tree
        root = cssselect2.ElementWrapper.from_xml_root(tree)
        style = parent.style if parent else css.parse_stylesheets(self, url)
        if element_id:
            for element in root.iter_subtree():
                if element.id == element_id:
                    root = element
                    self.xml_tree = element.etree_element
                    break
            else:
                raise TypeError(
                    'No tag with id="{}" found.'.format(element_id))
        super().__init__(
            root, style, self.url_fetcher, parent, parent_children, self.url,
github montaggroup / montag / pydb / ebook_metadata_tools / epub.py View on Github external
def get_metadata_from_opf_string(opf_content):
    result = {'author_names': []}

    def clean_string(string):
        if string is None:
            return None
        string = re.sub('  +', ' ', string)
        return string.strip()

    # noinspection PyBroadException
    try:
        root = defused_etree.fromstring(opf_content)
    except Exception:
        logger.error('Unable to parse opf xml')
        return result

    for main_element in root:
        logger.debug(u'looking at main element {}'.format(main_element.tag))

        if not re.match(".*metadata$", main_element.tag):
            continue

        for metadata_tag in main_element:
            text = clean_string(metadata_tag.text)
            if text is None:
                continue
            
            if re.match(".*title$", metadata_tag.tag):
github sphinx-contrib / datatemplates / sphinxcontrib / datatemplates / loaders.py View on Github external
def load_xml(source, absolute_resolved_path, **options):
    yield ET.parse(absolute_resolved_path).getroot()
github DefectDojo / django-DefectDojo / dojo / tools / zap / parser.py View on Github external
def parse_xml(self, xml_output):
        """
        Open and parse an xml file.

        TODO: Write custom parser to just read the nodes that we need instead of
        reading the whole file.

        @return xml_tree An xml tree instance. None if error.
        """
        try:
            tree = ET.parse(xml_output)
        except SyntaxError as se:
            raise se

        return tree
github archerysec / archerysec / networkscanners / views.py View on Github external
if request.method == "POST":
        project_id = request.POST.get("project_id")
        scanner = request.POST.get("scanner")
        xml_file = request.FILES['xmlfile']
        scan_ip = request.POST.get("scan_url")
        scan_id = uuid.uuid4()
        scan_status = "100"
        if scanner == "openvas":
            date_time = datetime.now()
            scan_dump = scan_save_db(scan_ip=scan_ip,
                                     scan_id=scan_id,
                                     date_time=date_time,
                                     project_id=project_id,
                                     scan_status=scan_status)
            scan_dump.save()
            tree = ET.parse(xml_file)
            root_xml = tree.getroot()
            OpenVas_Parser.xml_parser(project_id=project_id,
                                      scan_id=scan_id,
                                      root=root_xml)
            return HttpResponseRedirect("/networkscanners/")
        elif scanner == "nessus":
            date_time = datetime.now()
            scan_dump = nessus_scan_db(
                scan_ip=scan_ip,
                scan_id=scan_id,
                date_time=date_time,
                project_id=project_id,
                scan_status=scan_status
            )
            scan_dump.save()
            scan_dump.save()
github DefectDojo / django-DefectDojo / dojo / tools / nexpose / parser.py View on Github external
def parse_xml(self, xml_output):
        """
        Open and parse an xml file.

        TODO: Write custom parser to just read the nodes that we need instead of
        reading the whole file.

        @return xml_tree An xml tree instance. None if error.
        """
        try:
            tree = ET.parse(xml_output)
        except SyntaxError as se:
            raise se

        return tree
github fabaff / python-connect-box / connect_box / __init__.py View on Github external
async def async_get_devices(self):
        """Scan for new devices and return a list with found device IDs."""
        if self.token is None:
            await self.async_initialize_token()

        self.devices.clear()
        raw = await self._async_ws_get_function(CMD_DEVICES)

        try:
            xml_root = element_tree.fromstring(raw)
            mac_adresses: List[str] = [mac.text for mac in xml_root.iter("MACAddr")]
            hostnames: List[str] = [mac.text for mac in xml_root.iter("hostname")]
            ip_addresses: List[str] = [mac.text for mac in xml_root.iter("IPv4Addr")]
            interfaces: List[str] = [mac.text for mac in xml_root.iter("interface")]
            speeds: List[str] = [mac.text for mac in xml_root.iter("speed")]
            interface_ids: List[str] = [
                mac.text for mac in xml_root.iter("interfaceid")
            ]
            methods: List[str] = [mac.text for mac in xml_root.iter("method")]
            lease_times: List[str] = [mac.text for mac in xml_root.iter("leaseTime")]

            for (
                mac_address,
                hostname,
                ip_address,
                interface,
github pycontribs / jira / jira / client.py View on Github external
else:
            logging.warning(
                'This functionality is not available in Server version')
            return None
        r = self._session.get(
            url, headers=self._options['headers'])
        # This is weird.  I used to get xml, but now I'm getting json
        try:
            return json.loads(r.text)
        except Exception:
            import defusedxml.ElementTree as etree

            progress = {}
            try:
                root = etree.fromstring(r.text)
            except etree.ParseError as pe:
                logging.warning('Unable to find backup info.  You probably need to initiate a new backup. %s' % pe)
                return None
            for k in root.keys():
                progress[k] = root.get(k)
            return progress
github log2timeline / plaso / plaso / parsers / android_app_usage.py View on Github external
"""
    data = file_object.read(self._HEADER_READ_SIZE)
    if not data.startswith(b'