Python xml.etree.cElementTree.tostring() Examples

The following are 30 code examples of xml.etree.cElementTree.tostring(). 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.cElementTree , or try the search function .
Example #1
Source File: uistuff.py    From pychess with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, filename):
        # TODO: remove this when upstream fixes translations with Python3+Windows
        if sys.platform == "win32" and not conf.no_gettext:
            tree = ET.parse(addDataPrefix("glade/%s" % filename))
            for node in tree.iter():
                if 'translatable' in node.attrib:
                    node.text = _(node.text)
                    del node.attrib['translatable']
                if node.get('name') in ('pixbuf', 'logo'):
                    node.text = addDataPrefix("glade/%s" % node.text)
            xml_text = ET.tostring(tree.getroot(), encoding='unicode', method='xml')
            self.builder = Gtk.Builder.new_from_string(xml_text, -1)
        else:
            self.builder = Gtk.Builder()
            if not conf.no_gettext:
                self.builder.set_translation_domain("pychess")
            self.builder.add_from_file(addDataPrefix("glade/%s" % filename)) 
Example #2
Source File: accept_command.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def reset_rebuild_data(self, project):
        data = self.api.pseudometa_file_load('support_pkg_rebuild')
        if data is None:
            return

        root = ET.fromstring(data)
        for stg in root.findall('staging'):
            if stg.get('name') == project:
                stg.find('rebuild').text = 'unknown'
                stg.find('supportpkg').text = ''

        # reset accepted staging project rebuild state to unknown and clean up
        # supportpkg list
        content = ET.tostring(root)
        if content != data:
            self.api.pseudometa_file_save('support_pkg_rebuild', content, 'accept command update') 
Example #3
Source File: accept_command.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def reset_rebuild_data(self, project):
        data = self.api.pseudometa_file_load('support_pkg_rebuild')
        if data is None:
            return

        root = ET.fromstring(data)
        for stg in root.findall('staging'):
            if stg.get('name') == project:
                stg.find('rebuild').text = 'unknown'
                stg.find('supportpkg').text = ''

        # reset accepted staging project rebuild state to unknown and clean up
        # supportpkg list
        content = ET.tostring(root)
        if content != data:
            self.api.pseudometa_file_save('support_pkg_rebuild', content, 'accept command update') 
Example #4
Source File: freeze_command.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def create_bootstrap_aggregate_file(self):
        url = self.api.makeurl(['source', self.prj, 'bootstrap-copy', '_aggregate'])

        root = ET.Element('aggregatelist')
        a = ET.SubElement(root, 'aggregate',
                          {'project': '{}:0-Bootstrap'.format(self.api.crings)})

        for package in self.bootstrap_packages():
            p = ET.SubElement(a, 'package')
            p.text = package

        ET.SubElement(a, 'repository', {'target': 'bootstrap_copy', 'source': 'standard'})
        ET.SubElement(a, 'repository', {'target': 'standard', 'source': 'nothing'})
        ET.SubElement(a, 'repository', {'target': 'images', 'source': 'nothing'})

        self.api.retried_PUT(url, ET.tostring(root)) 
Example #5
Source File: freeze_command.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def create_bootstrap_aggregate_file(self):
        url = self.api.makeurl(['source', self.prj, 'bootstrap-copy', '_aggregate'])

        root = ET.Element('aggregatelist')
        a = ET.SubElement(root, 'aggregate',
                          {'project': '{}:0-Bootstrap'.format(self.api.crings)})

        for package in self.bootstrap_packages():
            p = ET.SubElement(a, 'package')
            p.text = package

        ET.SubElement(a, 'repository', {'target': 'bootstrap_copy', 'source': 'standard'})
        ET.SubElement(a, 'repository', {'target': 'standard', 'source': 'nothing'})
        ET.SubElement(a, 'repository', {'target': 'images', 'source': 'nothing'})

        self.api.retried_PUT(url, ET.tostring(root)) 
Example #6
Source File: compare_pkglist.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def check_diff(self, package, old_prj, new_prj):
        logging.debug('checking %s ...' % package)
        query = {'cmd': 'diff',
                 'view': 'xml',
                 'oproject': old_prj,
                 'opackage': package}
        u = makeurl(self.apiurl, ['source', new_prj, package], query=query)
        root = ET.parse(http_POST(u)).getroot()
        old_srcmd5 = root.findall('old')[0].get('srcmd5')
        logging.debug('%s old srcmd5 %s in %s' % (package, old_srcmd5, old_prj))
        new_srcmd5 = root.findall('new')[0].get('srcmd5')
        logging.debug('%s new srcmd5 %s in %s' % (package, new_srcmd5, new_prj))
        # Compare srcmd5
        if old_srcmd5 != new_srcmd5:
            # check if it has diff element
            diffs = root.findall('files/file/diff')
            if diffs:
                return ET.tostring(root)
        return False 
Example #7
Source File: spheniscidae.py    From houdini with MIT License 6 votes vote down vote up
def send_xml(self, xml_dict):
        data_root = Element('msg')
        data_root.set('t', 'sys')

        sub_element_parent = data_root
        for sub_element, sub_element_attribute in xml_dict.items():
            sub_element_object = SubElement(sub_element_parent, sub_element)

            if type(xml_dict[sub_element]) is dict:
                for sub_element_attribute_key, sub_element_attribute_value in xml_dict[sub_element].items():
                    sub_element_object.set(sub_element_attribute_key, sub_element_attribute_value)
            else:
                sub_element_object.text = xml_dict[sub_element]

            sub_element_parent = sub_element_object

        xml_data = tostring(data_root)
        await self.send_line(xml_data.decode('utf-8')) 
Example #8
Source File: modular_input.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _do_scheme(self):
        scheme = Scheme(self.title)
        scheme.description = self.description
        scheme.use_external_validation = self.use_external_validation
        scheme.streaming_mode = Scheme.streaming_mode_xml
        scheme.use_single_instance = self.use_single_instance

        for argument in self.extra_arguments():
            name = argument['name']
            title = argument.get('title', None)
            description = argument.get('description', None)
            validation = argument.get('validation', None)
            data_type = argument.get('data_type', Argument.data_type_string)
            required_on_edit = argument.get('required_on_edit', False)
            required_on_create = argument.get('required_on_create', False)

            scheme.add_argument(
                Argument(name, title=title, description=description,
                         validation=validation, data_type=data_type,
                         required_on_edit=required_on_edit,
                         required_on_create=required_on_create))

        return ET.tostring(scheme.to_xml(), encoding=SCHEME_ENCODING) 
Example #9
Source File: biarchtool.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def add_explicit_disable(self, wipebinaries=False):

        self._init_biarch_packages()

        resulturl = self.makeurl(['source', self.project])
        result = ET.fromstring(self.cached_GET(resulturl))

        for pkg in self.packages:

            changed = False

            logger.debug("processing %s", pkg)
            if not pkg in self.package_metas:
                logger.error("%s not found", pkg)
                continue
            pkgmeta = self.package_metas[pkg]

            build = pkgmeta.findall("./build")
            if not build:
                logger.debug('disable %s for %s', pkg, self.arch)
                bn = pkgmeta.find('build')
                if bn is None:
                    bn = ET.SubElement(pkgmeta, 'build')
                ET.SubElement(bn, 'disable', { 'arch': self.arch })
                changed = True

            if changed:
                try:
                    pkgmetaurl = self.makeurl(['source', self.project, pkg, '_meta'])
                    self.http_PUT(pkgmetaurl, data=ET.tostring(pkgmeta))
                    if self.caching:
                        self._invalidate__cached_GET(pkgmetaurl)
                    if wipebinaries:
                        self.http_POST(self.makeurl(['build', self.project], {
                            'cmd': 'wipe',
                            'arch': self.arch,
                            'package': pkg }))
                except HTTPError as e:
                    logger.error('failed to update %s: %s', pkg, e) 
Example #10
Source File: fcc_submitter.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def freeze(self):
        """Main method"""
        flink = ET.Element('frozenlinks')

        fl = ET.SubElement(flink, 'frozenlink', {'project': self.factory})
        ignored_sources = self.receive_sources(fl)
        if self.debug:
            logging.debug("Dump ignored source")
            for source in ignored_sources:
                logging.debug("Ignored source: %s" % source)

        url = makeurl(self.apiurl, ['source', FCC, '_project', '_frozenlinks'], {'meta': '1'})
        l = ET.tostring(flink)
        try:
            http_PUT(url, data=l)
        except HTTPError as e:
            raise e 
Example #11
Source File: modular_input.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _do_scheme(self):
        scheme = Scheme(self.title)
        scheme.description = self.description
        scheme.use_external_validation = self.use_external_validation
        scheme.streaming_mode = Scheme.streaming_mode_xml
        scheme.use_single_instance = self.use_single_instance

        for argument in self.extra_arguments():
            name = argument['name']
            title = argument.get('title', None)
            description = argument.get('description', None)
            validation = argument.get('validation', None)
            data_type = argument.get('data_type', Argument.data_type_string)
            required_on_edit = argument.get('required_on_edit', False)
            required_on_create = argument.get('required_on_create', False)

            scheme.add_argument(
                Argument(name, title=title, description=description,
                         validation=validation, data_type=data_type,
                         required_on_edit=required_on_edit,
                         required_on_create=required_on_create))

        return ET.tostring(scheme.to_xml(), encoding=SCHEME_ENCODING) 
Example #12
Source File: XMLExporter.py    From DownloaderForReddit with GNU General Public License v3.0 6 votes vote down vote up
def export_reddit_objects_to_xml(object_list, file_path):
    """
    Exports the supplied list of RedditObjects to an xml format with each xml element representing one reddit object
    with all of its relevant and formattable attributes.  Some attributes are omitted from export either due to the
    resulting file size or irrelevancy.
    :param object_list: A list of RedditObjects which are to be exported to an xml file.
    :param file_path: The path at which the xml file will be created.
    """
    root = et.Element('reddit_objects')
    user_root = et.SubElement(root, 'users')
    subreddit_root = et.SubElement(root, 'subreddits')
    for ro in object_list:
        if ro.object_type == 'USER':
            make_reddit_object_element(user_root, ro)
        else:
            make_reddit_object_element(subreddit_root, ro)
    xml = minidom.parseString(et.tostring(root)).toprettyxml(indent='    ')
    with open(file_path, mode='a', encoding='utf-8') as file:
        file.write(xml)
    logger.info('Exported reddit object list to xml file', extra={'export_count': len(object_list)}) 
Example #13
Source File: xml_util.py    From pyxcli with Apache License 2.0 5 votes vote down vote up
def __str__(self):
        return "Cannot parse XML (cannot find %s):\n%s" % (
            self.notFound, tostring(self.xml)) 
Example #14
Source File: workflow.py    From Gank-Alfred-Workflow with MIT License 5 votes vote down vote up
def send_feedback(self):
        """Print stored items to console/Alfred as XML."""
        root = ET.Element('items')
        for item in self._items:
            root.append(item.elem)
        sys.stdout.write('<?xml version="1.0" encoding="utf-8"?>\n')
        sys.stdout.write(ET.tostring(root).encode('utf-8'))
        sys.stdout.flush()

    ####################################################################
    # Updating methods
    #################################################################### 
Example #15
Source File: converter.py    From latex2mathml with MIT License 5 votes vote down vote up
def _convert(tree: Element) -> str:
    return unescape(tostring(tree, encoding="unicode")) 
Example #16
Source File: workflow.py    From alfred-workflow-toggle-airpods with MIT License 5 votes vote down vote up
def send_feedback(self):
        """Print stored items to console/Alfred as XML."""
        root = ET.Element('items')
        for item in self._items:
            root.append(item.elem)
        sys.stdout.write('<?xml version="1.0" encoding="utf-8"?>\n')
        sys.stdout.write(ET.tostring(root).encode('utf-8'))
        sys.stdout.flush()

    ####################################################################
    # Updating methods
    #################################################################### 
Example #17
Source File: xmlcombine.py    From funannotate with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(xml_files):
    first = None
    for filename in xml_files:
        data = cElementTree.parse(filename).getroot()
        if first is None:
            first = data
        else:
            first.extend(data)
    if first is not None:
        print(cElementTree.tostring(first)) 
Example #18
Source File: XMLExporter.py    From DownloaderForReddit with GNU General Public License v3.0 5 votes vote down vote up
def export_posts_to_xml(post_list, file_path):
    """
    Exports the supplied list of posts to an xml format with each xml element representing one post with all of its
    attributes.
    :param post_list: The list of posts that are to be formatted into an xml file.
    :param file_path: The path at which the xml file will be created.
    """
    root = et.Element('failed_posts')
    for post in post_list:
        make_post_element(root, post)
    xml = minidom.parseString(et.tostring(root)).toprettyxml(indent='    ')
    with open(file_path, 'a', encoding='utf-8') as file:
        file.write(xml)
    logger.info('Exported post list to xml file', extra={'export_count': len(post_list)}) 
Example #19
Source File: tei_reden.py    From SEM with MIT License 5 votes vote down vote up
def document_to_file(self, document, couples, output, encoding="utf-8", **kwargs):
        teiDocument = self.document_to_data(document, couples=couples)
        content = ET.tostring(teiDocument, encoding="utf-8").decode("utf-8")
        if is_string(output):
            with codecs.open(output, "w", "utf-8") as O:
                O.write(u'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
                O.write(content)
        else:
            output.write(u'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
            output.write(content) 
Example #20
Source File: export.py    From rosreestr2coord with MIT License 5 votes vote down vote up
def coords2kml(coords, attrs):

    if len(coords):
        kml = ET.Element("kml", attrib={"xmlns": "http://www.opengis.net/kml/2.2"})
        doc = ET.SubElement(kml, "Document")
        folder = ET.SubElement(doc, "Folder")
        ET.SubElement(folder, "name").text = "test"
        placemark = ET.SubElement(folder, "Placemark")

        style = ET.SubElement(placemark, "Style")

        line_style = ET.SubElement(style, "LineStyle")
        ET.SubElement(line_style, "color").text = "ff0000ff"

        poly_style = ET.SubElement(style, "PolyStyle")
        ET.SubElement(poly_style, "fill").text = "0"

        multi_geometry = ET.SubElement(placemark, "MultiGeometry")

        for i in range(len(coords)):

            polygon = ET.SubElement(multi_geometry, "Polygon")
            for j in range(len(coords[i])):
                if j:
                    boundary = ET.SubElement(polygon, "outerBoundaryIs")
                else:
                    # for holes
                    boundary = ET.SubElement(polygon, "innerBoundaryIs")
                xy = coords[i][j]
                xy.append(xy[0])
                linear_ring = ET.SubElement(boundary, "LinearRing")
                ET.SubElement(linear_ring, "coordinates").text = ' '.join(
                    map(lambda c: ','.join(map(str, c)), xy)
                )
        return ET.tostring(kml, encoding='utf8', method='xml')
    return False 
Example #21
Source File: workflow.py    From alfred-brightness with MIT License 5 votes vote down vote up
def send_feedback(self):
        """Print stored items to console/Alfred as XML."""
        root = ET.Element('items')
        for item in self._items:
            root.append(item.elem)
        sys.stdout.write('<?xml version="1.0" encoding="utf-8"?>\n')
        sys.stdout.write(ET.tostring(root).encode('utf-8'))
        sys.stdout.flush()

    ####################################################################
    # Updating methods
    #################################################################### 
Example #22
Source File: ShimCacheParser_ACP.py    From appcompatprocessor with Apache License 2.0 5 votes vote down vote up
def read_mir(xml_file, quiet=False):
    out_list = []
    tmp_list = []
    error = ""

    # Open the MIR output file.
    try:
        for (_, reg_item) in et.iterparse(xml_file, events=('end',)):
            if reg_item.tag != 'RegistryItem':
                continue

            path_name = reg_item.find("Path").text
            if not path_name:
                print "[-] Error XML missing Path"
                print et.tostring(reg_item)
                reg_item.clear()
                continue
            path_name = path_name.lower()

            # Check to see that we have the right registry value.
            if 'control\\session manager\\appcompatcache\\appcompatcache' in path_name \
                or 'control\\session manager\\appcompatibility\\appcompatcache' in path_name:
                # return the base64 decoded value data.
                bin_data = binascii.a2b_base64(reg_item.find('Value').text)
                tmp_list = read_cache(bin_data, quiet)

                if tmp_list:
                    for row in tmp_list:
                        if g_verbose:
                            row.append(path_name)
                        if row not in out_list:
                            out_list.append(row)
            reg_item.clear()
    except (AttributeError, TypeError, IOError),  err:
        error = "[-] Error reading MIR XML: %s" % str(err)
        print error
        return (error, None) 
Example #23
Source File: event.py    From splunk-ref-pas-code with Apache License 2.0 5 votes vote down vote up
def write_to(self, stream):
        """Write an XML representation of self, an ``Event`` object, to the given stream.

        The ``Event`` object will only be written if its data field is defined,
        otherwise a ``ValueError`` is raised.

        :param stream: stream to write XML to.
        """
        if self.data is None:
            raise ValueError("Events must have at least the data field set to be written to XML.")

        event = ET.Element("event")
        if self.stanza is not None:
            event.set("stanza", self.stanza)
        event.set("unbroken", str(int(self.unbroken)))

        # if a time isn't set, let Splunk guess by not creating a <time> element
        if self.time is not None:
            ET.SubElement(event, "time").text = str(self.time)

        # add all other subelements to this Event, represented by (tag, text)
        subelements = [
            ("source", self.source),
            ("sourcetype", self.sourceType),
            ("index", self.index),
            ("host", self.host),
            ("data", self.data)
        ]
        for node, value in subelements:
            if value is not None:
                ET.SubElement(event, node).text = value

        if self.done is not None:
            ET.SubElement(event, "done")

        stream.write(ET.tostring(event))
        stream.flush() 
Example #24
Source File: printers.py    From py-lua-parser with MIT License 5 votes vote down vote up
def get_xml_string(self, tree):
        xml = self.visit(tree)

        ast = ElementTree.Element("ast")
        doc = ElementTree.SubElement(ast, "doc")
        doc.append(xml)

        return minidom.parseString(ElementTree.tostring(doc)).toprettyxml(indent="   ") 
Example #25
Source File: etree.py    From OpenMTC with Eclipse Public License 1.0 5 votes vote down vote up
def tostring(element, encoding="utf-8", pretty_print=False):
        return _ts(element, encoding=encoding) 
Example #26
Source File: etree.py    From OpenMTC with Eclipse Public License 1.0 5 votes vote down vote up
def tostring(element, encoding="utf-8", pretty_print=False):
        return _ts(element, encoding=encoding, pretty_print=pretty_print) 
Example #27
Source File: tei_np.py    From SEM with MIT License 5 votes vote down vote up
def document_to_file(self, document, couples, output, encoding="utf-8", **kwargs):
        teiCorpus = self.document_to_data(document, couples=couples)
        with open(output, "w") as O:
            O.write(u'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
            O.write(ET.tostring(teiCorpus, encoding="utf-8"))
            #O.write(self.document_to_unicode(document, couples, encoding=encoding, **kwargs)) 
Example #28
Source File: tei_np.py    From SEM with MIT License 5 votes vote down vote up
def document_to_unicode(self, document, couples, encoding="utf-8", **kwargs):
        return u'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n' \
               + ET.tostring(self.document_to_data(document, couples), encoding=encoding) 
Example #29
Source File: gate.py    From SEM with MIT License 5 votes vote down vote up
def document_to_file(self, document, couples, output, encoding="utf-8", **kwargs):
        gateDocument = self.document_to_data(document, couples=couples)
        content = ET.tostring(gateDocument, encoding="utf-8").decode(u"utf-8")
        if is_string(output):
            with codecs.open(output, u"w", encoding) as O:
                O.write(u'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
                O.write(content)
                #O.write(self.document_to_unicode(document, couples, encoding=encoding, **kwargs))
        else:
            output.write(u'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
            output.write(content) 
Example #30
Source File: workflow.py    From wechat-alfred-workflow with MIT License 5 votes vote down vote up
def send_feedback(self):
        """Print stored items to console/Alfred as XML."""
        root = ET.Element('items')
        for item in self._items:
            root.append(item.elem)
        sys.stdout.write('<?xml version="1.0" encoding="utf-8"?>\n')
        sys.stdout.write(ET.tostring(root).encode('utf-8'))
        sys.stdout.flush()

    ####################################################################
    # Updating methods
    ####################################################################