当前位置: 首页>>代码示例>>Python>>正文


Python etree.tostring方法代码示例

本文整理汇总了Python中lxml.etree.tostring方法的典型用法代码示例。如果您正苦于以下问题:Python etree.tostring方法的具体用法?Python etree.tostring怎么用?Python etree.tostring使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在lxml.etree的用法示例。


在下文中一共展示了etree.tostring方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: create_group

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def create_group(self, name, users=[]):

        meta = """
        <group>
          <title>{}</title>
        </group>
        """.format(name)

        if len(users):
            root = ET.fromstring(meta)
            persons = ET.SubElement(root, 'person')
            for user in users:
                ET.SubElement(persons, 'person', {'userid': user} )
            meta = ET.tostring(root)

        if not name in self.groups:
            self.groups.append(name)
        url = osc.core.makeurl(APIURL, ['group', name])
        osc.core.http_PUT(url, data=meta) 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:21,代码来源:OBSLocal.py

示例2: androaxml_main

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def androaxml_main(inp, outp=None, resource=None):
    ret_type = androconf.is_android(inp)
    if ret_type == "APK":
        a = apk.APK(inp)
        if resource:
            if resource not in a.files:
                print("The APK does not contain a file called '{}'".format(resource), file=sys.stderr)
                sys.exit(1)

            axml = AXMLPrinter(a.get_file(resource)).get_xml_obj()
        else:
            axml = a.get_android_manifest_xml()
    elif ".xml" in inp:
        axml = AXMLPrinter(read(inp)).get_xml_obj()
    else:
        print("Unknown file type")
        sys.exit(1)

    buff = etree.tostring(axml, pretty_print=True, encoding="utf-8")
    if outp:
        with open(outp, "wb") as fd:
            fd.write(buff)
    else:
        sys.stdout.write(highlight(buff.decode("UTF-8"), get_lexer_by_name("xml"), TerminalFormatter())) 
开发者ID:amimo,项目名称:dcc,代码行数:26,代码来源:main.py

示例3: pretty_print

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def pretty_print(xml):
    """Prints beautiful XML-Code

    This function gets a string containing the xml, an object of
    List[lxml.etree.Element] or directly a lxml element.

    Print it with good readable format.

    Arguments:
        xml (str, List[lxml.etree.Element] or lxml.etree.Element):
            xml as string,
            List[lxml.etree.Element] or directly a lxml element.

    """
    if isinstance(xml, list):
        for item in xml:
            if etree.iselement(item):
                print(etree.tostring(item, pretty_print=True).decode("utf-8"))
            else:
                print(item)
    elif etree.iselement(xml):
        print(etree.tostring(xml, pretty_print=True).decode("utf-8"))
    elif isinstance(xml, str):
        tree = secET.fromstring(xml)
        print(etree.tostring(tree, pretty_print=True).decode("utf-8")) 
开发者ID:greenbone,项目名称:python-gvm,代码行数:27,代码来源:xml.py

示例4: parseXMLxpathSearch

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def parseXMLxpathSearch(xml_source, xpathString):
#---------------------------------------------------------------------------------

    return_values = []

    try:
        root = etree.XML(xml_source)

        data_points = root.xpath(xpathString)
    
        for data in data_points:
            return_values.append(etree.tostring(data))
            data.clear()

    except:
        pass

    return return_values

#---------------------------------------------------------------------------------
# parse XML and return value asked (designed for errors via stdout) 
开发者ID:kenb123,项目名称:Basic-Expression-Lexicon-Variation-Algorithms-BELVA,代码行数:23,代码来源:belvaParseXML.py

示例5: parseHTMLxpathSearch

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def parseHTMLxpathSearch(http_source, xpathString):
#---------------------------------------------------------------------------------

    return_values = []


    http_source= str(http_source).replace('\x00','')
    try:
        html = lxml.html.fromstring(http_source)

        for data in html.xpath(xpathString):
            return_values.append(etree.tostring(data.content))
            data.clear()

    except:
        pass

    return return_values



#---------------------------------------------------------------------------------
# parse HTML and return value asked 
开发者ID:kenb123,项目名称:Basic-Expression-Lexicon-Variation-Algorithms-BELVA,代码行数:25,代码来源:belvaParseXML.py

示例6: create_package_container

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def create_package_container(self, project, package, meta=None, disable_build=False):
        """
        Creates a package container without any fields in project/package
        :param project: project to create it
        :param package: package name
        :param meta: package metadata
        :param disable_build: should the package be created with build
                              flag disabled
        """
        if not meta:
            meta = '<package name="{}"><title/><description/></package>'
            meta = meta.format(package)

        if disable_build:
            root = ET.fromstring(meta)
            elm = ET.SubElement(root, 'build')
            ET.SubElement(elm, 'disable')
            meta = ET.tostring(root)

        url = self.makeurl(['source', project, package, '_meta'])
        http_PUT(url, data=meta) 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:23,代码来源:stagingapi.py

示例7: delete_to_prj

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def delete_to_prj(self, act, project):
        """
        Hides Package in project
        :param act: action for delete request
        :param project: project to hide in
        """

        tar_pkg = act.tgt_package
        # need to get the subpackages before we wipe it
        sub_packages = self.get_sub_packages(tar_pkg, project)
        self.create_and_wipe_package(project, tar_pkg)

        for sub_pkg in sub_packages:
            self.create_and_wipe_package(project, sub_pkg)

            # create a link so unselect can find it
            root = ET.Element('link', package=tar_pkg, project=project)
            url = self.makeurl(['source', project, sub_pkg, '_link'])
            http_PUT(url, data=ET.tostring(root))

        return tar_pkg 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:23,代码来源:stagingapi.py

示例8: ensure_staging_archs

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def ensure_staging_archs(self, project):
        meta = ET.parse(http_GET(self.project_meta_url(project)))
        repository = meta.find('repository[@name="{}"]'.format(self.cmain_repo))

        changed = False
        for arch in self.cstaging_archs:
            if not repository.xpath('./arch[text()="{}"]'.format(arch)):
                elm = ET.SubElement(repository, 'arch')
                elm.text = arch
                changed = True

        if not changed:
            return

        meta = ET.tostring(meta)
        http_PUT(self.project_meta_url(project), data=meta) 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:18,代码来源:stagingapi.py

示例9: write_all_groups

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def write_all_groups(self):
        self._check_supplements()
        summary = dict()
        archs = ['*'] + self.all_architectures
        for name in self.groups:
            group = self.groups[name]
            if not group.solved:
                continue
            summary[name] = group.summary()
            fn = '{}.group'.format(group.name)
            with open(os.path.join(self.output_dir, fn), 'w') as fh:
                comment = group.comment
                for arch in archs:
                    x = group.toxml(arch, self.ignore_broken, comment)
                    # only comment first time
                    comment = None
                    x = ET.tostring(x, pretty_print=True, encoding='unicode')
                    x = re.sub(r'\s*<!-- reason:', ' <!-- reason:', x)
                    fh.write(x)
        return summary 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:22,代码来源:tool.py

示例10: add_bugowner

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def add_bugowner(self, package, owner):
        url = self.makeurl(['source', self.project, package, '_meta'])
        root = ET.fromstring(self.cached_GET(url))
        idname = 'userid' if owner.kind == 'person' else 'groupid'
        # XXX: can't use 'and' here to filter for bugowner too
        exists = root.findall('./{}[@{}="{}"]'.format(owner.kind, idname, owner.name))
        for node in exists:
            if node.get('role') == 'bugowner':
                logger.debug("%s/%s already has %s %s", self.project, package, owner.kind, owner.name)
            return

        node = ET.SubElement(root, owner.kind)
        node.set(idname, owner.name)
        node.set('role', 'bugowner')

        data = ET.tostring(root)
        logger.debug(data)
        self.http_PUT(url, data=data) 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:20,代码来源:bugowner.py

示例11: __init__

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def __init__(self, name, project, devel_project=None):
        self.name = name
        self.project = project

        meta = """
            <package project="{1}" name="{0}">
              <title></title>
              <description></description>
            </package>""".format(self.name, self.project.name)

        if devel_project:
            root = ET.fromstring(meta)
            ET.SubElement(root, 'devel', { 'project': devel_project })
            meta = ET.tostring(root)

        url = osc.core.make_meta_url('pkg', (self.project.name, self.name), APIURL)
        osc.core.http_PUT(url, data=meta)
        print('created {}/{}'.format(self.project.name, self.name))
        self.project.add_package(self)

    # delete from instance 
开发者ID:openSUSE,项目名称:openSUSE-release-tools,代码行数:23,代码来源:OBSLocal.py

示例12: _render_response

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def _render_response(self, response_data, request_id):
        response_el = ec2utils.dict_to_xml(
            {'return': 'true'} if response_data is True else response_data,
            self.action + 'Response')
        response_el.attrib['xmlns'] = ('http://ec2.amazonaws.com/doc/%s/'
                                       % self.version)
        request_id_el = etree.Element('requestId')
        request_id_el.text = request_id
        response_el.insert(0, request_id_el)

        response = etree.tostring(response_el, pretty_print=True)

        # Don't write private key to log
        if self.action != "CreateKeyPair":
            LOG.debug(response)
        else:
            LOG.debug("CreateKeyPair: Return Private Key")

        return response 
开发者ID:openstack,项目名称:ec2-api,代码行数:21,代码来源:apirequest.py

示例13: _format_vpn_connection

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def _format_vpn_connection(vpn_connection, customer_gateways, os_ikepolicies,
                           os_ipsecpolicies, os_ipsec_site_connections,
                           external_ips):
    config_dict = _format_customer_config(
        vpn_connection, customer_gateways, os_ikepolicies, os_ipsecpolicies,
        os_ipsec_site_connections, external_ips)
    config = ec2utils.dict_to_xml(config_dict, 'vpn_connection')
    config.attrib['id'] = vpn_connection['id']
    config_str = etree.tostring(config, xml_declaration=True, encoding='UTF-8',
                                pretty_print=True)
    return {'vpnConnectionId': vpn_connection['id'],
            'vpnGatewayId': vpn_connection['vpn_gateway_id'],
            'customerGatewayId': vpn_connection['customer_gateway_id'],
            'state': 'available',
            'type': 'ipsec.1',
            'routes': [{'destinationCidrBlock': cidr,
                        'state': 'available'}
                       for cidr in vpn_connection['cidrs']],
            'vgwTelemetry': [],
            'options': {'staticRoutesOnly': True},
            'customerGatewayConfiguration': config_str} 
开发者ID:openstack,项目名称:ec2-api,代码行数:23,代码来源:vpn_connection.py

示例14: addpositionstodict

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def addpositionstodict(gendict):
    print("Downloading position information from web...")
    for accidwithloc in tqdm(gendict):
        if 'Start' in gendict[accidwithloc]:
            continue
        accid = '_'.join(accidwithloc.split('_')[:-1])
        url = ('http://crispr.i2bc.paris-saclay.fr/crispr/crispr_db.php?'
               'checked%5B%5D={}'.format(accid))
        page = requests.get(url)
        htmltable = html.fromstring(page.content).xpath(
            "//table[normalize-space(@class)='primary_table']")[1]
        strtable = etree.tostring(htmltable)
        # converts to pandas df and then to numpy array then drop titles
        arrtable = pandas.read_html(strtable)[0].as_matrix()[2:]
        for row in arrtable:
            if row[0] in gendict:
                gendict[row[0]]['Start'] = row[2]
                gendict[row[0]]['Stop'] = row[3]
            else:
                if row[1] != 'questionable':
                    print("Can't find %s in local files" % row[0])
    return gendict 
开发者ID:phageParser,项目名称:phageParser,代码行数:24,代码来源:populate.py

示例15: dump_dolfin_xml

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import tostring [as 别名]
def dump_dolfin_xml(filename, V, F):
    root = etree.Element("dolfin")
    mesh = etree.SubElement(root, "mesh", celltype="triangle", dim="2")
    vertices = etree.SubElement(mesh, "vertices", size="%d" % V.shape[0])
    for i in range(V.shape[0]):
        etree.SubElement(vertices, "vertex", index="%d" % i, x="%f" % V[i, 0],
            y="%f" % V[i, 1], z="0")
    faces = etree.SubElement(mesh, "cells", size="%d" % F.shape[0])
    for i in range(F.shape[0]):
        etree.SubElement(faces, "triangle", index="%d" % i, v0="%d" % F[i, 0],
            v1="%d" % F[i, 1], v2="%d" % F[i, 2])

    with open(filename, 'wb') as f:
        f.write(etree.tostring(root, pretty_print=True)) 
开发者ID:zfergus,项目名称:fenics-topopt,代码行数:16,代码来源:triangulate.py


注:本文中的lxml.etree.tostring方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。