python类tostring()的实例源码

__init__.py 文件源码 项目:unsonic 作者: redshodan 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def makeBody(self, attrs, child, status):
        body = ET.Element("subsonic-response")
        attrs_ = {"status": "ok" if status is True else "failed",
                  "xmlns": "http://subsonic.org/restapi",
                  "version": PROTOCOL_VERSION,
                  "unsonic": UNSONIC_PROTOCOL_VERSION}
        attrs_.update(attrs)
        for key, value in attrs_.items():
            body.set(key, value)
        if status is not True and status is not False:
            error = ET.Element("error")
            if isinstance(status[0], tuple):
                error.set("code", status[0][0])
                error.set("message", "%s: %s" % (status[0][1], status[1]))
            else:
                error.set("code", status[0])
                error.set("message", status[1])
            body.append(error)
        if child is not None:
            body.append(child)
        return "%s%s\n" % (XML_HEADER, ET.tostring(body).decode("utf-8"))
test_xml_etree.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def parseliteral():
    """
    >>> element = ET.XML("<html><body>text</body></html>")
    >>> ET.ElementTree(element).write(sys.stdout, encoding='unicode')
    <html><body>text</body></html>
    >>> element = ET.fromstring("<html><body>text</body></html>")
    >>> ET.ElementTree(element).write(sys.stdout, encoding='unicode')
    <html><body>text</body></html>
    >>> sequence = ["<html><body>", "text</bo", "dy></html>"]
    >>> element = ET.fromstringlist(sequence)
    >>> ET.tostring(element)
    b'<html><body>text</body></html>'
    >>> b"".join(ET.tostringlist(element))
    b'<html><body>text</body></html>'
    >>> ET.tostring(element, "ascii")
    b"<?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'
    """
test_xml_etree.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def processinginstruction():
    """
    Test ProcessingInstruction directly

    >>> ET.tostring(ET.ProcessingInstruction('test', 'instruction'))
    b'<?test instruction?>'
    >>> ET.tostring(ET.PI('test', 'instruction'))
    b'<?test instruction?>'

    Issue #2746

    >>> ET.tostring(ET.PI('test', '<testing&>'))
    b'<?test <testing&>?>'
    >>> ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin1')
    b"<?xml version='1.0' encoding='latin1'?>\\n<?test <testing&>\\xe3?>"
    """

#
# xinclude tests (samples from appendix C of the xinclude specification)
utils.py 文件源码 项目:RobotFrameworkReporter 作者: ivanitskiy 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _extarct_only_robot(xmlfile):
    """remove from file not robot's elements
    robot elements are: 'suite' 'statistics' 'errors'
    """

    original_doc = ET.parse(xmlfile)
    root = original_doc.getroot()
    devices = root.find("devices")
    if devices is not None:
        root.remove(devices)

    source = StringIO(ET.tostring(root))
    ets = ETSource(source)
    execution_result = ExecutionResultBuilder(ets).build(Result())
    patched_file = File(BytesIO(force_bytes(source.getvalue())), name=xmlfile.name)
    return (execution_result, patched_file)
workflow.py 文件源码 项目:alfred-mpd 作者: deanishe 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
    ####################################################################
utils.py 文件源码 项目:ironic-staging-drivers 作者: openstack 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def build_soap_xml(items, namespace=None):
    """Build a SOAP XML.

    :param items: a list of dictionaries where key is the element name
                  and the value is the element text.
    :param namespace: the namespace for the elements, None for no
                      namespace. Defaults to None
    :returns: a XML string.

    """

    def _create_element(name, value=None):
        xml_string = name
        if namespace:
            xml_string = "{%(namespace)s}%(item)s" % {'namespace': namespace,
                                                      'item': xml_string}

        element = ElementTree.Element(xml_string)
        element.text = value
        return element

    soap_namespace = "http://www.w3.org/2003/05/soap-envelope"
    envelope_element = ElementTree.Element("{%s}Envelope" % soap_namespace)
    body_element = ElementTree.Element("{%s}Body" % soap_namespace)

    for item in items:
        for i in item:
            insertion_point = _create_element(i)
            if isinstance(item[i], dict):
                for j, value in item[i].items():
                    insertion_point.append(_create_element(j, value))
            else:
                insertion_point.text = item[i]

            body_element.append(insertion_point)

    envelope_element.append(body_element)
    return ElementTree.tostring(envelope_element)
akamai_publish_dir.py 文件源码 项目:ccu_and_eccu_publish 作者: gaofubin 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def eccu_doc_for_purge_dir(path_to_purge):
    root = ET.Element('eccu')
    parent = root
    names = (name for name in path_to_purge.split('/') if name)
    for name in names:
        parent = ET.SubElement(parent, 'match:recursive-dirs', {'value': name})
    revalidate = ET.SubElement(parent, 'revalidate')
    revalidate.text = 'now'
    return ET.tostring(root, encoding='ascii') #'<?xml version="1.0"?>\n' + ET.tostring(root)
    #xml = StringIO()
    #xml.write('<?xml version="1.0"?>\n')
    #xml.write(ET.tostring(root))
    #return xml
event.py 文件源码 项目:mongodb-monitoring 作者: jruaux 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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:
            ET.SubElement(event, "done")

        stream.write(ET.tostring(event))
        stream.flush()
workflow.py 文件源码 项目:Gank-Alfred-Workflow 作者: hujiaweibujidao 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
    ####################################################################
workflow.py 文件源码 项目:Gank-Alfred-Workflow 作者: hujiaweibujidao 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
    ####################################################################
ntb_nitf.py 文件源码 项目:superdesk-ntb 作者: superdesk 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def build_body_html(xml):
    elements = []
    for elem in xml.find('body/body.content'):
        if elem.tag == 'p' and elem.get('class') == 'lead':
            continue
        elements.append(ET.tostring(elem, encoding='unicode'))
    return ''.join(elements)
virtualbmc.py 文件源码 项目:virtualbmc 作者: umago 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def set_boot_device(self, bootdevice):
        LOG.debug('Set boot device called for %(domain)s with boot '
                  'device "%(bootdev)s"', {'domain': self.domain_name,
                                           'bootdev': bootdevice})
        device = SET_BOOT_DEVICES_MAP.get(bootdevice)
        if device is None:
            return 0xd5

        with utils.libvirt_open(**self._conn_args) as conn:
            domain = utils.get_libvirt_domain(conn, self.domain_name)
            tree = ET.fromstring(domain.XMLDesc())

            for os_element in tree.findall('os'):
                # Remove all "boot" elements
                for boot_element in os_element.findall('boot'):
                    os_element.remove(boot_element)

                # Add a new boot element with the request boot device
                boot_element = ET.SubElement(os_element, 'boot')
                boot_element.set('dev', device)

            try:
                conn.defineXML(ET.tostring(tree))
            except libvirt.libvirtError as e:
                LOG.error('Failed setting the boot device  %(bootdev)s for '
                          'domain %(domain)s', {'bootdev': device,
                                                'domain': self.domain_name})
recipe-521902.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __write(self):
        h = open(self.out, 'w')
        h.write("import xml.etree.ElementTree as ET\n\n")

        # prints namespace constants
        h.writelines(["%s = '%s'\n" % (v, k) for k, v in self.constants.items()])
        h.write("\n")

        h.write("def build(**kwargs):\n\t")

        h.write("\n\t".join(self.lines))
        h.write("\n\treturn ET.tostring(%s)\n\n" % self.root)

        h.write("if __name__ == '__main__': print build()")
        h.close()
event.py 文件源码 项目:Splunk_CBER_App 作者: MHaggis 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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:
            ET.SubElement(event, "done")

        stream.write(ET.tostring(event))
        stream.flush()
cppcheck.py 文件源码 项目:SoCFoundationFlow 作者: mattaw 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _save_xml_report(self, s):
        '''use cppcheck xml result string, add the command string used to invoke cppcheck
        and save as xml file.
        '''
        header = '%s\n' % s.splitlines()[0]
        root = ElementTree.fromstring(s)
        cmd = ElementTree.SubElement(root.find('cppcheck'), 'cmd')
        cmd.text = str(self.cmd)
        body = ElementTree.tostring(root)
        node = self.generator.path.get_bld().find_or_declare('cppcheck.xml')
        node.write(header + body)
cppcheck.py 文件源码 项目:SoCFoundationFlow 作者: mattaw 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _create_html_file(self, sourcefile, htmlfile, errors):
        name = self.generator.get_name()
        root = ElementTree.fromstring(CPPCHECK_HTML_FILE)
        title = root.find('head/title')
        title.text = 'cppcheck - report - %s' % name

        body = root.find('body')
        for div in body.findall('div'):
            if div.get('id') == 'page':
                page = div
                break
        for div in page.findall('div'):
            if div.get('id') == 'header':
                h1 = div.find('h1')
                h1.text = 'cppcheck report - %s' % name
            if div.get('id') == 'content':
                content = div
                srcnode = self.generator.bld.root.find_node(sourcefile)
                hl_lines = [e['line'] for e in errors if e.has_key('line')]
                formatter = CppcheckHtmlFormatter(linenos=True, style='colorful', hl_lines=hl_lines, lineanchors='line')
                formatter.errors = [e for e in errors if e.has_key('line')]
                css_style_defs = formatter.get_style_defs('.highlight')
                lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
                s = pygments.highlight(srcnode.read(), lexer, formatter)
                table = ElementTree.fromstring(s)
                content.append(table)

        s = ElementTree.tostring(root, method='html')
        s = CCPCHECK_HTML_TYPE + s
        node = self.generator.path.get_bld().find_or_declare(htmlfile)
        node.write(s)
        return css_style_defs
cppcheck.py 文件源码 项目:SoCFoundationFlow 作者: mattaw 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _save_xml_report(self, s):
        '''use cppcheck xml result string, add the command string used to invoke cppcheck
        and save as xml file.
        '''
        header = '%s\n' % s.splitlines()[0]
        root = ElementTree.fromstring(s)
        cmd = ElementTree.SubElement(root.find('cppcheck'), 'cmd')
        cmd.text = str(self.cmd)
        body = ElementTree.tostring(root)
        node = self.generator.path.get_bld().find_or_declare('cppcheck.xml')
        node.write(header + body)
cppcheck.py 文件源码 项目:SoCFoundationFlow 作者: mattaw 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _create_html_file(self, sourcefile, htmlfile, errors):
        name = self.generator.get_name()
        root = ElementTree.fromstring(CPPCHECK_HTML_FILE)
        title = root.find('head/title')
        title.text = 'cppcheck - report - %s' % name

        body = root.find('body')
        for div in body.findall('div'):
            if div.get('id') == 'page':
                page = div
                break
        for div in page.findall('div'):
            if div.get('id') == 'header':
                h1 = div.find('h1')
                h1.text = 'cppcheck report - %s' % name
            if div.get('id') == 'content':
                content = div
                srcnode = self.generator.bld.root.find_node(sourcefile)
                hl_lines = [e['line'] for e in errors if e.has_key('line')]
                formatter = CppcheckHtmlFormatter(linenos=True, style='colorful', hl_lines=hl_lines, lineanchors='line')
                formatter.errors = [e for e in errors if e.has_key('line')]
                css_style_defs = formatter.get_style_defs('.highlight')
                lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
                s = pygments.highlight(srcnode.read(), lexer, formatter)
                table = ElementTree.fromstring(s)
                content.append(table)

        s = ElementTree.tostring(root, method='html')
        s = CCPCHECK_HTML_TYPE + s
        node = self.generator.path.get_bld().find_or_declare(htmlfile)
        node.write(s)
        return css_style_defs
cppcheck.py 文件源码 项目:SoCFoundationFlow 作者: mattaw 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _save_xml_report(self, s):
        '''use cppcheck xml result string, add the command string used to invoke cppcheck
        and save as xml file.
        '''
        header = '%s\n' % s.splitlines()[0]
        root = ElementTree.fromstring(s)
        cmd = ElementTree.SubElement(root.find('cppcheck'), 'cmd')
        cmd.text = str(self.cmd)
        body = ElementTree.tostring(root)
        node = self.generator.path.get_bld().find_or_declare('cppcheck.xml')
        node.write(header + body)
cppcheck.py 文件源码 项目:SoCFoundationFlow 作者: mattaw 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _create_html_file(self, sourcefile, htmlfile, errors):
        name = self.generator.get_name()
        root = ElementTree.fromstring(CPPCHECK_HTML_FILE)
        title = root.find('head/title')
        title.text = 'cppcheck - report - %s' % name

        body = root.find('body')
        for div in body.findall('div'):
            if div.get('id') == 'page':
                page = div
                break
        for div in page.findall('div'):
            if div.get('id') == 'header':
                h1 = div.find('h1')
                h1.text = 'cppcheck report - %s' % name
            if div.get('id') == 'content':
                content = div
                srcnode = self.generator.bld.root.find_node(sourcefile)
                hl_lines = [e['line'] for e in errors if e.has_key('line')]
                formatter = CppcheckHtmlFormatter(linenos=True, style='colorful', hl_lines=hl_lines, lineanchors='line')
                formatter.errors = [e for e in errors if e.has_key('line')]
                css_style_defs = formatter.get_style_defs('.highlight')
                lexer = pygments.lexers.guess_lexer_for_filename(sourcefile, "")
                s = pygments.highlight(srcnode.read(), lexer, formatter)
                table = ElementTree.fromstring(s)
                content.append(table)

        s = ElementTree.tostring(root, method='html')
        s = CCPCHECK_HTML_TYPE + s
        node = self.generator.path.get_bld().find_or_declare(htmlfile)
        node.write(s)
        return css_style_defs


问题


面经


文章

微信
公众号

扫码关注公众号