Python xml.etree.ElementTree.fromstringlist() Examples

The following are 10 code examples of xml.etree.ElementTree.fromstringlist(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.etree.ElementTree , or try the search function .
Example #1
Source File: test_xml_etree.py    From BinderFilter with MIT License 6 votes vote down vote up
def parseliteral():
    """
    >>> element = ET.XML("<html><body>text</body></html>")
    >>> ET.ElementTree(element).write(sys.stdout)
    <html><body>text</body></html>
    >>> element = ET.fromstring("<html><body>text</body></html>")
    >>> ET.ElementTree(element).write(sys.stdout)
    <html><body>text</body></html>
    >>> sequence = ["<html><body>", "text</bo", "dy></html>"]
    >>> element = ET.fromstringlist(sequence)
    >>> print ET.tostring(element)
    <html><body>text</body></html>
    >>> print "".join(ET.tostringlist(element))
    <html><body>text</body></html>
    >>> ET.tostring(element, "ascii")
    "<?xml version='1.0' encoding='ascii'?>\\n<html><body>text</body></html>"
    >>> _, ids = ET.XMLID("<html><body>text</body></html>")
    >>> len(ids)
    0
    >>> _, ids = ET.XMLID("<html><body id='body'>text</body></html>")
    >>> len(ids)
    1
    >>> ids["body"].tag
    'body'
    """ 
Example #2
Source File: test_xml_etree.py    From oss-ftp with MIT License 6 votes vote down vote up
def parseliteral():
    """
    >>> element = ET.XML("<html><body>text</body></html>")
    >>> ET.ElementTree(element).write(sys.stdout)
    <html><body>text</body></html>
    >>> element = ET.fromstring("<html><body>text</body></html>")
    >>> ET.ElementTree(element).write(sys.stdout)
    <html><body>text</body></html>
    >>> sequence = ["<html><body>", "text</bo", "dy></html>"]
    >>> element = ET.fromstringlist(sequence)
    >>> print ET.tostring(element)
    <html><body>text</body></html>
    >>> print "".join(ET.tostringlist(element))
    <html><body>text</body></html>
    >>> ET.tostring(element, "ascii")
    "<?xml version='1.0' encoding='ascii'?>\\n<html><body>text</body></html>"
    >>> _, ids = ET.XMLID("<html><body>text</body></html>")
    >>> len(ids)
    0
    >>> _, ids = ET.XMLID("<html><body id='body'>text</body></html>")
    >>> len(ids)
    1
    >>> ids["body"].tag
    'body'
    """ 
Example #3
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def parseliteral():
    """
    >>> element = ET.XML("<html><body>text</body></html>")
    >>> ET.ElementTree(element).write(sys.stdout)
    <html><body>text</body></html>
    >>> element = ET.fromstring("<html><body>text</body></html>")
    >>> ET.ElementTree(element).write(sys.stdout)
    <html><body>text</body></html>
    >>> sequence = ["<html><body>", "text</bo", "dy></html>"]
    >>> element = ET.fromstringlist(sequence)
    >>> print ET.tostring(element)
    <html><body>text</body></html>
    >>> print "".join(ET.tostringlist(element))
    <html><body>text</body></html>
    >>> ET.tostring(element, "ascii")
    "<?xml version='1.0' encoding='ascii'?>\\n<html><body>text</body></html>"
    >>> _, ids = ET.XMLID("<html><body>text</body></html>")
    >>> len(ids)
    0
    >>> _, ids = ET.XMLID("<html><body id='body'>text</body></html>")
    >>> len(ids)
    1
    >>> ids["body"].tag
    'body'
    """ 
Example #4
Source File: .ycm_extra_conf.py    From EasyClangComplete with MIT License 6 votes vote down vote up
def standardize_file_target(file_target):
    """For file targets that are not source files, return the target that generated them.

    This is needed because rdeps of generated files do not include targets that reference
    their generating rules.
    https://github.com/bazelbuild/bazel/issues/4949
    """

    query_result = bazel_query(['--output=xml', file_target])
    if not query_result:
        sys.exit("Empty query response for {}. It is probably not handled by bazel".format(file_target))

    target_xml = ElementTree.fromstringlist(query_result.split('\n'))
    source_element = target_xml.find('source-file')
    if source_element is not None:
        return file_target

    generated_element = target_xml.find('generated-file')
    if generated_element is not None:
        return generated_element.get('generating-rule')

    sys.exit("Error parsing query xml for " + file_target + ":\n" + query_result) 
Example #5
Source File: owncloud.py    From pyocclient with MIT License 5 votes vote down vote up
def get_resource_body(self):
        if self.res is not None:
            import xml.etree.ElementTree as ElementTree
            try:
                root_element = ElementTree.fromstringlist(self.res.content)
                if root_element.tag == 'message':
                    return root_element.text
            except ET.ParseError:
                return self.res.content
        else:
            return None 
Example #6
Source File: file_helpers.py    From Retropie-CRT-Edition with GNU General Public License v3.0 5 votes vote down vote up
def get_xml_value_esconfig(p_sFindMask, p_sFile = ES_CFG_FILE):
    """ 
    Find value for element in es_settings.cfg of Emulationstation
    by default. This file must have a <root> to be parsed. This
    function will try to read as it is, if not, create root of xml
    and look for the element.
    """
    p_bParsed = False
    p_sValue = None
    if not os.path.isfile(p_sFile):
        return None
    try:
        tree = ET.parse(p_sFile)
        root = tree.getroot()
        p_bParsed = True
    except:
        pass
    # create root to parse as regular xml
    if not p_bParsed:
        file = filter(None, open(p_sFile, "r").read().splitlines())
        for line in file:        
            if "xml" in line and "version" in line:
                file.remove(line)
        file.insert(0, "<root>\n")
        file[-1] = file[-1].strip()+"\n"
        file.append("</root>\n")
        root = ET.fromstringlist(file)    
    # search the element
    for child in root:
        try:
            if child.attrib["name"] == p_sFindMask:
                p_sValue = child.attrib["value"]
                return p_sValue
        except:
            pass
    return False 
Example #7
Source File: podcast_archiver.py    From podcast-archiver with MIT License 5 votes vote down vote up
def parseOpmlFile(self, opml):
        with opml as file:
            tree = etree.fromstringlist(file)

        for feed in [node.get('xmlUrl') for node
                     in tree.findall("*/outline/[@type='rss']")
                     if node.get('xmlUrl') is not None]:

            self.addFeed(feed) 
Example #8
Source File: cbmc.py    From benchexec with Apache License 2.0 4 votes vote down vote up
def parse_XML(self, output, returncode, isTimeout):
        # an empty tag cannot be parsed into a tree
        def sanitizeXML(s):
            return s.replace("<>", "<emptyTag>").replace("</>", "</emptyTag>")

        try:
            tree = ElementTree.fromstringlist(map(sanitizeXML, output))
            status = tree.findtext("cprover-status")

            if status is None:

                def isErrorMessage(msg):
                    return msg.get("type", None) == "ERROR"

                messages = list(filter(isErrorMessage, tree.getiterator("message")))
                if messages:
                    # for now, use only the first error message if there are several
                    msg = messages[0].findtext("text")
                    if msg == "Out of memory":
                        status = "OUT OF MEMORY"
                    elif msg == "SAT checker ran out of memory":
                        status = "OUT OF MEMORY"
                    elif msg:
                        status = "ERROR ({0})".format(msg)
                    else:
                        status = "ERROR"
                else:
                    status = "INVALID OUTPUT"

            elif status == "FAILURE":
                assert returncode == 10
                reason = tree.find("goto_trace").find("failure").findtext("reason")
                if not reason:
                    reason = tree.find("goto_trace").find("failure").get("reason")
                if "unwinding assertion" in reason:
                    status = result.RESULT_UNKNOWN
                else:
                    status = result.RESULT_FALSE_REACH

            elif status == "SUCCESS":
                assert returncode == 0
                if "--unwinding-assertions" in self.options:
                    status = result.RESULT_TRUE_PROP
                else:
                    status = result.RESULT_UNKNOWN

        except Exception:
            if isTimeout:
                # in this case an exception is expected as the XML is invalid
                status = "TIMEOUT"
            elif "Minisat::OutOfMemoryException" in output:
                status = "OUT OF MEMORY"
            else:
                status = "INVALID OUTPUT"
                logging.exception(
                    "Error parsing CBMC output for returncode %d", returncode
                )

        return status 
Example #9
Source File: file_helpers.py    From Retropie-CRT-Edition with GNU General Public License v3.0 4 votes vote down vote up
def set_xml_value_esconfig(p_sFindMask, p_sValue, p_sFile = ES_CFG_FILE):
    """ 
    Find element and set a value in es_settings.cfg of Emulationstation
    by default. This file must have a <root> to be parsed. This function
    will try to read as it is, if not, create root of this xml file, and
    look for the element and change its value with modify_line function.
    """
    p_bParsed = False
    p_sLineToFind = None
    p_sNewLine = None
    p_sValueToChange = None
    if not os.path.isfile(p_sFile):
        return None
    try:
        tree = ET.parse(p_sFile)
        root = tree.getroot()
        p_bParsed = True
    except:
        pass
    # create root to parse as regular xml
    if not p_bParsed:
        file = filter(None, open(p_sFile, "r").read().splitlines())
        for line in file:        
            if "xml" in line and "version" in line:
                file.remove(line)
        file.insert(0, "<root>\n")
        file[-1] = file[-1].strip()+"\n"
        file.append("</root>\n")
        root = ET.fromstringlist(file)    
    # search the element and save value and line
    for child in root:
        try:
            if child.attrib["name"] == p_sFindMask:
                p_sValueToChange = child.attrib["value"]
                p_sLineToFind = ET.tostring(child).strip()
                break
        except:
            pass
    # if found replace line with the new value
    if p_sLineToFind:
        p_sNewLine = p_sLineToFind.replace(p_sValueToChange, p_sValue)
        return modify_line(p_sFile, p_sLineToFind, p_sNewLine)
    return False 
Example #10
Source File: data_processor.py    From SceneClassification with GNU General Public License v3.0 4 votes vote down vote up
def xml_extract(xml_path, seg_label_path):
    """
    extract information in xml file
    Input:
        xml_path: string; the path of the xml file
        seg_label_path: string; the path of the npy file to be stored
    Return:
        image_label: int; the class of this image
    Note:
        in npy file, it is stored as np3darray (w, h, class_number + 1) in np.bool type
        the last layer of class is background
    """
    with open(xml_path) as f:
        it = itertools.chain('<root>', f, '</root>')
        root = ET.fromstringlist(it)
    seg_label = np.zeros([CLASS_NUMBER, 128, 128], dtype=np.uint8)

    for obj in root:
        if obj.tag == 'class':
            image_label = int(obj.text)
        if obj.tag == 'objects':
            polygon_list = []
            label = obj.find('class')
            label = int(label.text)
            polygon = obj.find('polygon')
            for point in polygon:
                x = point.find('x')
                x = int(x.text) - 1
                y = point.find('y')
                y = int(y.text) - 1
                pt = np.array([[[x,y]]], dtype=np.int32)
                polygon_list.append(pt)
            polygon = np.concatenate(polygon_list, axis=1)
            cv2.fillPoly(seg_label[label], polygon, 255)
    seg_label = seg_label.astype(bool)
    background = np.ones([128,128], dtype=bool) - np.sum(seg_label, axis=0).astype(bool)
    seg_label = np.concatenate([seg_label, np.expand_dims(background, axis=0)], axis=0)
    seg_label = np.packbits(seg_label, axis=-1)

    """
    for i in range(seg_label.shape[0]):
        if np.sum(seg_label[i]) != 0:
            cv2.imshow('image', seg_label[i].astype(np.uint8) * 255)
            cv2.waitKey(0)
            cv2.destroyAllWindows()
    """

    np.save(seg_label_path, seg_label)
    return image_label