python类ElementTree()的实例源码

__init__.py 文件源码 项目:st2docs 作者: StackStorm 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def create_sitemap(app, exception):
    """Generates the sitemap.xml from the collected HTML page links"""
    if (not app.config['html_theme_options'].get('base_url', '') or
        exception is not None or not app.sitemap_links):
        return

    filename = app.outdir + "/sitemap.xml"
    print "Generating sitemap.xml in %s" % filename

    root = ET.Element("urlset")
    root.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")

    for link in app.sitemap_links:
        url = ET.SubElement(root, "url")
        ET.SubElement(url, "loc").text = link

    ET.ElementTree(root).write(filename)
test_xml_etree.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def file_init():
    """
    >>> import StringIO

    >>> stringfile = StringIO.StringIO(SAMPLE_XML)
    >>> tree = ET.ElementTree(file=stringfile)
    >>> tree.find("tag").tag
    'tag'
    >>> tree.find("section/tag").tag
    'tag'

    >>> tree = ET.ElementTree(file=SIMPLE_XMLFILE)
    >>> tree.find("element").tag
    'element'
    >>> tree.find("element/../empty-element").tag
    'empty-element'
    """
test_xml_etree.py 文件源码 项目:oil 作者: oilshell 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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'
    """
test_xml_etree.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def file_init():
    """
    >>> import StringIO

    >>> stringfile = StringIO.StringIO(SAMPLE_XML)
    >>> tree = ET.ElementTree(file=stringfile)
    >>> tree.find("tag").tag
    'tag'
    >>> tree.find("section/tag").tag
    'tag'

    >>> tree = ET.ElementTree(file=SIMPLE_XMLFILE)
    >>> tree.find("element").tag
    'element'
    >>> tree.find("element/../empty-element").tag
    'empty-element'
    """
test_xml_etree.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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'
    """
test_libvirt_utils.py 文件源码 项目:daisy 作者: opnfv 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_modify_vm_disk_file():
    template = os.path.join(WORKSPACE, 'templates/physical_environment/vms/daisy.xml')
    tree = ET.ElementTree(file=template)
    root = tree.getroot()
    disk_path1 = os.path.join('/home/qemu/vms', 'daisy_test1.qcow2')
    disk_path2 = os.path.join('/home/qemu/vms', 'daisy_test2.qcow2')
    disks_path = [disk_path1, disk_path2]
    modify_vm_disk_file(root, disks_path)
    devices = root.find('./devices')
    disks = [disk for disk in devices.findall('disk') if disk.attrib['device'] == 'disk']
    assert len(disks) == len(disks_path)
    for i in range(len(disks)):
        assert disks[i].attrib['type'] == 'file'
        driver = disks[i].find('driver')
        assert driver.attrib['name'] == 'qemu' and driver.attrib['type'] == 'qcow2'
        target = disks[i].find('target')
        assert target.attrib['bus'] == 'ide'
        source = disks[i].find('source')
        assert source.attrib['file'] == disks_path[i]
test_libvirt_utils.py 文件源码 项目:daisy 作者: opnfv 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_modify_vm_bridge():
    template = os.path.join(WORKSPACE, 'templates/virtual_environment/vms/daisy.xml')
    tree = ET.ElementTree(file=template)
    root = tree.getroot()
    bridge = 'daisy_test'
    modify_vm_bridge(root, bridge)
    devices = root.find('./devices')
    is_match = False
    for interface in devices.findall('interface'):
        source = interface.find('source')
        if interface.attrib.get('type', None) == 'bridge' \
                and source is not None \
                and source.attrib.get('bridge', None) == bridge:
            is_match = True
            break
    assert is_match
libvirt_utils.py 文件源码 项目:daisy 作者: opnfv 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def delete_virtual_network(network_xml):
    LI('Begin to find and delete network %s' % network_xml)
    tree = ET.ElementTree(file=network_xml)
    root = tree.getroot()
    names = root.findall('./name')
    assert len(names) == 1
    name = names[0].text

    result = 0
    conn = libvirt.open('qemu:///system')

    for net in conn.listAllNetworks():
        if name == net.name():
            if net.isActive():
                net.destroy()
                LI('Network %s is destroyed' % name)
            net.undefine()
            LI('Network %s is deleted' % name)
            result = 1
            break
    conn.close()
    if not result:
        LI('Network %s is not found' % name)
testlink_parser.py 文件源码 项目:xmind2testlink 作者: tobyqin 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def to_testlink_xml_content(testsuite):
    assert isinstance(testsuite, TestSuite)
    root_suite = Element(Tags.testsuite)
    root_suite.set(Attributes.name, testsuite.name)
    cache['testcase_count'] = 0

    for suite in testsuite.sub_suites:
        assert isinstance(suite, TestSuite)

        if should_skip(suite.name):
            continue

        suite_element = SubElement(root_suite, Tags.testsuite)
        suite_element.set(Attributes.name, suite.name)
        build_text_field(suite_element, Tags.details, suite.details)
        build_testcase_xml(suite, suite_element)

    tree = ElementTree.ElementTree(root_suite)
    f = BytesIO()
    tree.write(f, encoding='utf-8', xml_declaration=True)
    return f.getvalue()
iof.py 文件源码 项目:pysport 作者: sportorg 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def indent(elem, level=0):
    """
        import xml.etree.ElementTree as ET

        elem = ET.Element('MyElem')

        indent(elem)
    """
    i = "\n" + level*"\t"
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "\t"
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i
eventExtFromRaw.py 文件源码 项目:NNED 作者: qolina 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def extractEvents(filename):

    xmlTree = ElementTree(file=filename[:-3]+"apf.xml")
    #root = xmlTree.getroot()

    eventArrOneDoc = []
    for eventEle in xmlTree.iter(tag="event"):
        #print eventEle
        #print eventEle.tag, eventEle.attrib
        eventArr = extractEvent(eventEle)
        #print eventArr
        eventArrOneDoc.extend(eventArr)

    #print event2str(eventArrOneDoc[0], "\t")
    return eventArrOneDoc

# forth_layer(event): [optional]event_argument, event_mention
# fifth_layer(event_mention): extent, ldc_scope, anchor, [optional]event_mention_argument
# sixth_layer(event_mention_argument): extent
# event_v1 = [sentence_ldc_scope, eventType, eventSubType, anchorText, (argText, role), (argText, role), ...]
# event_v2 = [(sentence_ldc_scope, index), eventType, eventSubType, (anchorText, index), (argText, role, index), (argText, role, index), ...]
deputies_dataset.py 文件源码 项目:serenata-toolbox 作者: datasciencebr 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def fetch(self):
        """
        Fetches the list of deputies for the current term.
        """
        xml = urllib.request.urlopen(self.URL)

        tree = ET.ElementTree(file=xml)
        records = self._parse_deputies(tree.getroot())

        df = pd.DataFrame(records, columns=(
            'congressperson_id',
            'budget_id',
            'condition',
            'congressperson_document',
            'civil_name',
            'congressperson_name',
            'picture_url',
            'gender',
            'state',
            'party',
            'phone_number',
            'email'
        ))
        return self._translate(df)
presences_dataset.py 文件源码 项目:serenata-toolbox 作者: datasciencebr 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def _all_presences(self, deputies, start_date, end_date):
        error_count = 0
        for i, deputy in deputies.iterrows():
            log.debug(i, deputy.congressperson_name, deputy.congressperson_document)
            url = self.URL.format(start_date, end_date, deputy.congressperson_document)
            xml = self._try_fetch_xml(10, url)

            if xml is None:
                error_count += 1
            else:
                root = ET.ElementTree(file=xml).getroot()
                for presence in self._parse_deputy_presences(root):
                    yield presence

            time.sleep(self.sleep_interval)

        log.debug("\nErrored fetching", error_count, "deputy presences")
test_converters.py 文件源码 项目:PyKED 作者: pr-omethe-us 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def test_error_rcm_pressurerise(self):
        """Test for appropriate error if RCM file has pressure rise.
        """
        file_path = os.path.join('testfile_rcm.xml')
        filename = pkg_resources.resource_filename(__name__, file_path)

        # add pressure rise to common properties
        tree = etree.parse(filename)
        root = tree.getroot()
        properties = root.find('commonProperties')
        prop = etree.SubElement(properties, 'property')
        prop.set('name', 'pressure rise')
        prop.set('units', '1/ms')
        prop_value = etree.SubElement(prop, 'value')
        prop_value.text = '0.10'

        # write new file, and try to load
        et = etree.ElementTree(root)
        with TemporaryDirectory() as temp_dir:
            filename = os.path.join(temp_dir, 'test.xml')
            et.write(filename, encoding='utf-8', xml_declaration=True)

            with pytest.raises(KeywordError) as excinfo:
                ReSpecTh_to_ChemKED(filename)
            assert 'Pressure rise cannot be defined for RCM.' in str(excinfo.value)
generate_index.py 文件源码 项目:docs 作者: hasura 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def onFinishBuilding(app, exception):
    currentVersion = app.env.config["version"]
    if "latest_docs_version" in app.env.config["html_context"].keys():
        latestVersion = app.env.config["html_context"]["latest_docs_version"]
    else:
        latestVersion = "dev"
    base_domain = app.env.config["html_context"]["SITEMAP_DOMAIN"]

    file_path = "./_build/algolia_index/index.json"
    sitemap_path = "./_build/sitemap/sitemap_" + currentVersion + ".xml"

    checkDirectory(file_path)
    checkDirectory(sitemap_path)

    f = open(file_path, 'w+')

    root = ET.Element("urlset")
    root.set("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9")

    for link in indexObjs:
        url = ET.SubElement(root, "url")
        ET.SubElement(url, "loc").text = base_domain + str(currentVersion) + "/" + link["url"]
        ET.SubElement(url, "changefreq").text = "daily"
        ET.SubElement(url, "priority").text = "1" if ( currentVersion == latestVersion ) else "0.5"

    ET.ElementTree(root).write(sitemap_path)

    f.write(json.dumps(indexObjs))
recipe-576536.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def CDATA(text=None):
    """
    A CDATA element factory function that uses the function itself as the tag
    (based on the Comment factory function in the ElementTree implementation).
    """
    element = etree.Element(CDATA)
    element.text = text
    return element

# We're replacing the _write method of the ElementTree class so that it would 
# recognize and correctly print out CDATA sections.
recipe-580752.py 文件源码 项目:code 作者: ActiveState 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def parse_xml(self, xml):
        self._element_tree = ET.ElementTree(ET.fromstring(xml))

        self.clear()
        self._walk_xml(self._element_tree.getroot())
utils.py 文件源码 项目:django-cml 作者: ArtemiusUA 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_xml(self):
        f = BytesIO()
        tree = ET.ElementTree(self.root)
        tree.write(f, encoding='windows-1251', xml_declaration=True)
        return f.getvalue()
ArgsWindow.py 文件源码 项目:mama 作者: maateen 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def saveTree(self,store):
        """
        @description: save the treeview in the mama.xml file

        @param: store
            the listStore attach to the treeview
        """
        # if there is still an entry in the model
        config = expanduser('~') +'/.config/mama/mama.xml'
        try:
            if not os.path.exists(os.path.dirname(config)):
                os.makedirs(os.path.dirname(config))

            root = ET.Element("data")
            if len(store) != 0:
                for i in range(len(store)):
                    iter = store.get_iter(i)
                    if store[iter][0] != '' and store[iter][1] != '':
                        for s in store[iter][0].split('|'):
                            s = s.lower()
                            s = s.replace('*',' ')
                            Type = ET.SubElement(root, "entry")
                            Type.set("name",unicode(store[iter][2],"utf-8"))
                            Key = ET.SubElement(Type, "key")
                            Key.text = unicode(s,"utf-8")
                            Command = ET.SubElement(Type, "command")
                            Command.text = unicode(store[iter][1],"utf-8")
                            Linker = ET.SubElement(Type, "linker")
                            Spacebyplus = ET.SubElement(Type, "spacebyplus")
                            if store[iter][3] is not None or store[iter][4] is not None:
                                Linker.text = unicode(store[iter][3],"utf-8")
                                Spacebyplus.text = unicode(store[iter][4],"utf-8")

            tree = ET.ElementTree(root).write(config,encoding="utf-8",xml_declaration=True)

        except IOError:
            print("Unable to write the file")
InternalWindow.py 文件源码 项目:mama 作者: maateen 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def saveTree(self, store):
        """
        @description: save the treeview in the mama.xml file

        @param: store
            the listStore attach to the treeview
        """
        # if there is still an entry in the model
        config = expanduser('~') + '/.config/mama/mama.xml'
        try:
            if not os.path.exists(os.path.dirname(config)):
                os.makedirs(os.path.dirname(config))

            root = ET.Element("data")
            if len(store) != 0:
                for i in range(len(store)):
                    iter = store.get_iter(i)
                    if store[iter][0] != '' and store[iter][1] != '':
                        for s in store[iter][0].split('|'):
                            s = s.lower()
                            s = s.replace('*', ' ')
                            Type = ET.SubElement(root, "entry")
                            Type.set("name", unicode(store[iter][2], "utf-8"))
                            Key = ET.SubElement(Type, "key")
                            Key.text = unicode(s, "utf-8")
                            Command = ET.SubElement(Type, "command")
                            Command.text = unicode(store[iter][1], "utf-8")
                            Linker = ET.SubElement(Type, "linker")
                            Spacebyplus = ET.SubElement(Type, "spacebyplus")
                            if store[iter][3] is not None and store[iter][
                                4] is not None:
                                Linker.text = unicode(store[iter][3], "utf-8")
                                Spacebyplus.text = unicode(store[iter][4],
                                                           "utf-8")

            tree = ET.ElementTree(root).write(config, encoding="utf-8",
                                              xml_declaration=True)

        except IOError:
            print("Unable to write the file")


问题


面经


文章

微信
公众号

扫码关注公众号