How to use the defusedxml.ElementTree.parse 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 Sketchy502 / SDV-Summary / sdv / generateSavegame.py View on Github external
def findPlayer(saveFileLocation,read_data=False):
	if read_data == False:
		root = ET.parse(saveFileLocation).getroot()
	else:
		root = ET.fromstring(saveFileLocation)
	player = root.find("player")
	return player
github bgroff / kala-app / django_kala / api / basecamp_classic / projects / parsers.py View on Github external
def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as XML and returns the resulting data.
        """

        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
        parser = etree.DefusedXMLParser(encoding=encoding)
        try:
            tree = etree.parse(stream, parser=parser, forbid_dtd=True)
        except (etree.ParseError, ValueError) as exc:
            raise ParseError(detail=str(exc))
        data = self._xml_convert(tree.getroot())

        return data
github Sketchy502 / SDV-Summary / sdv / analyse_saves.py View on Github external
def main():
	for f, file in enumerate(files[0:1]):
		ns = "{http://www.w3.org/2001/XMLSchema-instance}"
		locations = parse(file).getroot().find('locations').findall('GameLocation')
		assert locations[1].attrib[ns+'type'] == 'Farm'
		farm = locations[1]
		print(str(f)+' of '+str(len(files)-1))
		structure.update(moveRecursivelyOverXml(farm))
	# print structure
	return structure
github DefectDojo / django-DefectDojo / dojo / tools / wapiti / parser.py View on Github external
def __init__(self, file, test):
        self.dupes = dict()
        self.items = ()
        if file is None:
            return

        tree = ET.parse(file)
        # get root of tree.
        root = tree.getroot()
        # check if it is
        if 'report' not in root.tag:
            raise NamespaceErr("This doesn't seem to be a valid Wapiti xml file.")

        for result in root.findall('report/results/result'):
            family = result.find('nvt/family').text
            # check if vulnerability found in family then proceed.
            if "vulnerability" in family:
                # get host
                host = result.find('host').text
                # get title
                title = result.find('nvt/name').text
                # get cve
                cve = result.find('nvt/cve').text
github insarlab / MintPy / mintpy / utils / readfile.py View on Github external
def read_isce_xml(fname, standardize=True):
    """Read ISCE .xml file into a python dict structure."""
    root = ET.parse(fname).getroot()
    xmlDict = {}

    # imageFile, e.g. filt_fine.unw.xml
    if root.tag.startswith('image'):
        for child in root.findall('property'):
            key = child.get('name')
            value = child.find('value').text
            xmlDict[key] = value

        # Read lat/lon info for geocoded file
        # in form: root/component coordinate*/property name/value
        for coord_name, prefix in zip(['coordinate1', 'coordinate2'], ['X', 'Y']):
            child = root.find("./component[@name='{}']".format(coord_name))
            v_step  = float(child.find("./property[@name='delta']").find('value').text)
            v_first = float(child.find("./property[@name='startingvalue']").find('value').text)
            if abs(v_step) < 1. and abs(v_step) > 1e-7:
github DefectDojo / django-DefectDojo / dojo / tools / openscap / parser.py View on Github external
def __init__(self, file, test):
        self.dupes = dict()
        self.items = ()
        if file is None:
            return

        tree = ET.parse(file)
        # get root of tree.
        root = tree.getroot()
        namespace = self.get_namespace(root)
        # go to test result
        test_result = tree.find('./{0}TestResult'.format(namespace))
        ips = []
        # append all target in a list.
        for ip in test_result.findall('./{0}target-address'.format(namespace)):
            ips.append(ip.text)
        # check if xml file hash correct root or not.
        if 'Benchmark' not in root.tag:
            raise NamespaceErr("This doesn't seem to be a valid Openscap vulnerability scan xml file.")

        # run both rule, and rule-result in parallel so that we can get title for failed test from rule.
        for rule, rule_result in zip(root.findall('./{0}Rule'.format(namespace)), test_result.findall('./{0}rule-result'.format(namespace))):
            cves = []
github insarlab / MintPy / mintpy / prep_fringe.py View on Github external
def read_vrt_info(vrt_file):
    '''
    Read info from VRT file

    Parameters: vrt_file - str, geometry vrt file
    Returns:    box      - tuple of 4 int, bounding box in (x0, y0, x1, y1)
                src_dir  - str, path of geometry directory with binary data files
    '''
    root = ET.parse(vrt_file).getroot()

    # get VRT tag structure
    prefix_cand = ['VRTRasterBand/SimpleSource', 'VRTRasterBand']
    prefix_list = [prefix for prefix  in prefix_cand
                   if root.find(prefix + '/SourceFilename') is not None]
    if len(prefix_list) > 0:
        prefix = prefix_list[0]
    else:
        msg = 'No pre-defined tag structure found in file: {}!'.format(vrt_file)
        msg += '\nPre-defined tag structure candidates:'
        for prefix in prefix_cand:
            msg += '\n    {}/SourceFilename'.format(prefix)
        raise ValueError(msg)

    # box
    type_tag = root.find(prefix + '/SrcRect')
github openstack / cinder / cinder / volume / drivers / huawei / huawei_conf.py View on Github external
def _encode_authentication(self):
        need_encode = False
        tree = ET.parse(self.conf.cinder_huawei_conf_file)
        xml_root = tree.getroot()
        name_node = xml_root.find('Storage/UserName')
        pwd_node = xml_root.find('Storage/UserPassword')
        if (name_node is not None
                and not name_node.text.startswith('!$$$')):
            name_node.text = '!$$$' + base64.b64encode(name_node.text)
            need_encode = True
        if (pwd_node is not None
                and not pwd_node.text.startswith('!$$$')):
            pwd_node.text = '!$$$' + base64.b64encode(pwd_node.text)
            need_encode = True

        if need_encode:
            utils.execute('chmod',
                          '600',
                          self.conf.cinder_huawei_conf_file,
github bgroff / kala-app / django_kala / api / basecamp_classic / projects / parsers.py View on Github external
def parse(self, stream, media_type=None, parser_context=None):
        """
        Parses the incoming bytestream as XML and returns the resulting data.
        """

        parser_context = parser_context or {}
        encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
        parser = etree.DefusedXMLParser(encoding=encoding)
        try:
            tree = etree.parse(stream, parser=parser, forbid_dtd=True)
        except (etree.ParseError, ValueError) as exc:
            raise ParseError(detail=str(exc))
        data = self._xml_convert(tree.getroot())

        return data
github log2timeline / plaso / plaso / parsers / opera.py View on Github external
"""
    data = file_object.read(self._HEADER_READ_SIZE)
    if not data.startswith(b'