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


Python SubElement.text方法代码示例

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


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

示例1: items_xml

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def items_xml():
    """Returns all the items as an XML file.

    Research for this function came from:
        https://pymotw.com/2/xml/etree/ElementTree/create.html
    """
    session = connect_to_database()
    categories = session.query(Category).all()

    root = Element('catalog')

    for category in categories:
        cat_tag = SubElement(root,
                             'category',
                             {'id':str(category.id), 'name':category.name})

        items = session.query(Item).filter_by(category=category).all()

        for item in items:
            item_tag = SubElement(cat_tag, 'item', {'id':str(item.id)})
            name_tag = SubElement(item_tag, 'name')
            name_tag.text = item.name
            desc_tag = SubElement(item_tag, 'description')
            desc_tag.text = item.description
            desc_tag = SubElement(item_tag, 'quantity')
            desc_tag.text = str(item.quantity)

    session.close()

    # Return the XML with a 2 space indent to make it more human readable.
    return parseString(tostring(root, 'utf-8')).toprettyxml(indent='  ')
开发者ID:SteveWooding,项目名称:fullstack-nanodegree-vm,代码行数:33,代码来源:xml_generator.py

示例2: MDK4AddGroup

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def MDK4AddGroup(ProjectFiles, parent, name, files, project_path):
    group = SubElement(parent, 'Group')
    group_name = SubElement(group, 'GroupName')
    group_name.text = name

    for f in files:
        fn = f.rfile()
        name = fn.name
        path = os.path.dirname(fn.abspath)

        basename = os.path.basename(path)
        path = _make_path_relative(project_path, path)
        path = os.path.join(path, name)
        
        files = SubElement(group, 'Files')
        file = SubElement(files, 'File')
        file_name = SubElement(file, 'FileName')
        name = os.path.basename(path)
        if ProjectFiles.count(name):
            name = basename + '_' + name
        ProjectFiles.append(name)
        file_name.text = name.decode(fs_encoding)
        file_type = SubElement(file, 'FileType')
        file_type.text = '%d' % _get_filetype(name)
        file_path = SubElement(file, 'FilePath')
        
        file_path.text = path.decode(fs_encoding)
开发者ID:Ksangho,项目名称:stm32bootloader,代码行数:29,代码来源:building.py

示例3: brandsCatalogXML

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def brandsCatalogXML(brand_id):
    if 'username' not in login_session:
        response = make_response(json.dumps("You are not authorized, Login is required"), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    else:
        brand = session.query(Brand).filter_by(id=brand_id).one()
        items = session.query(Item).filter_by(brand_id=brand_id).all()
    
    root = Element('html')
    for i in items:
        body = SubElement(root, 'body')
        ID = SubElement(body, 'ID')
        ID.text = str(i.id)
        name = SubElement(body, 'name')
        name.text = i.name
        price = SubElement(body, 'price')
        price.text = i.price
        description = SubElement(body, 'description')
        description.text = i.description
        image = SubElement(body, 'image')
        image.text = i.image
        print tostring(root)

    return app.response_class(tostring(root), mimetype='application/xml')
开发者ID:konqlonq,项目名称:Project-3,代码行数:27,代码来源:project.py

示例4: updateLine

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def updateLine(firstrow, method, attr):
    root, body = getBaseXML()
    action = SubElement(body, 'ns:' + method)
    for i in range(len(attr)):
        if '-' in firstrow[i]:
            # pattern;partition;altnum-nummask;altnum-partition
            #<altnum>
            #  <nummask>XXXX</nummask>
            #  <partition>CLUSTERDN</partition>
            #</altnum>
            parentchild = firstrow[i].split('-')
            #altnum
            parent = parentchild[0]
            #nummask
            child = parentchild[1]

            #<altnum>
            l1 = SubElement(action, parent)
            #<altnum><nummask>
            l2 = SubElement(l1, child)
            #<altnum><nummask>XXXX
            l2.text = attr[i]
        else:
            l1 = SubElement(action, firstrow[i])
            l1.text = attr[i]

    xmldata = ElementTree.tostring(root, encoding='utf-8')

    logger.info('Updating Line ' + attr[0])
    for i in range(len(firstrow)):
        logger.debug(firstrow[i] + ': ' + attr[i])

    result = runAxl(method, xmldata)
    logger.info(result)
开发者ID:MrCollaborator,项目名称:CiscoUCScripts,代码行数:36,代码来源:updateAttribute_py2.py

示例5: generateXML

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
    def generateXML(self, os):
        # Structure of document is:
        #
        # <CALDAV:mkcalendar>
        #   <DAV:prop>
        #     <<each property as elements>>
        #   </DAV:prop>
        # </CALDAV:mkcalendar>

        # <CALDAV:mkcalendar> element
        mkcalendar = Element(caldavxml.mkcalendar)

        # <DAV:prop> element
        prop = SubElement(mkcalendar, davxml.prop)

        # <DAV:displayname> element
        if self.displayname:
            displayname = SubElement(prop, davxml.displayname)
            displayname.text = self.displayname

        # <CalDAV:calendar-description> element
        if self.description:
            description = SubElement(prop, caldavxml.calendar_description)
            description.text = self.description

        # <CalDAV:timezone> element
        if self.timezone:
            timezone = SubElement(prop, caldavxml.calendar_timezone)
            timezone.text = self.timezone

        # Now we have the complete document, so write it out (no indentation)
        xmldoc = BetterElementTree(mkcalendar)
        xmldoc.writeUTF8(os)
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:35,代码来源:makecalendar.py

示例6: story_feed

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def story_feed(request, story):
    story = Story.objects.get(slug=story)
    rss = Element('rss')
    rss.set("version","2.0")

    channel = SubElement(rss,'channel')

    title = SubElement(channel,'title')
    title.text = story.title

    link = SubElement(channel,'link')
    link.text = request.build_absolute_uri(reverse("story"))

    desc = SubElement(channel,'description')
    desc.text = story.description

    chapters = story.chapters.all()

    for index in chapters:
        item = SubElement(channel,'item')

        title_c = SubElement(item,'title')
        title_c.text = index.title
        
        link = SubElement(item,'link')
        link.text = request.build_absolute_uri(index.get_absolute_url())

    return HttpResponse(tostring(rss, encoding='UTF-8'))
开发者ID:gitter-badger,项目名称:fictionhub,代码行数:30,代码来源:views.py

示例7: execute

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
  def execute(self, mappings, source):
    """Writes the given language code/name mappings to Android XML resource files.

    source = string indicating source of the data, for example, 'cldr'
    mappings = list of dictionaries containing mappings"""

    # In order to be able to to localize a particular, limited set of words across multiple
    # languages, here we define a list of language codes to support for every resource file
    # generated. Where localized language names are missing, a place holder is printed. If
    # ['*'] is specified, then all available language code/name pairs are generated.
    COVERAGE_LIST = ['*']
    
    # Get language names in English as a dict for inclusion in XML comments
    english_pairs = {}
    for entry in mappings:
      for k, v in entry.iteritems():
        if k == 'en':
          english_pairs = v
          break
    
    for entry in mappings:
      for k, v in entry.iteritems():
        dir = os.path.join(os.path.dirname(__file__), self.get_directory(source) +
                           "../" + source + "-android/values-" + k)
        if not os.path.exists(dir):
          os.makedirs(dir)
        with open(dir + "/arrays.xml", "w") as f:
          top = Element('resources')
          if k in english_pairs.keys():
            top_comment = ElementTree.Comment(' ' + english_pairs[k].decode('utf-8') + ' (' + k + ') ')
          else:
            top_comment = ElementTree.Comment(' ' + k + ' ')
          top.append(top_comment)
          child = SubElement(top, 'string-array')          
          child.attrib['name'] = 'languages_all'
          
          if '*' not in COVERAGE_LIST:
            # Iterate through only those codes in COVERAGE_LIST
            for lang_code in COVERAGE_LIST:
              if lang_code in english_pairs.keys():
                comment = ElementTree.Comment(' ' + lang_code + ' - ' + english_pairs[lang_code].decode('utf-8') + ' ')
              else:
                comment = ElementTree.Comment(' ' + lang_code + ' ')
              child.append(comment)
              entry = SubElement(child, 'item')
              if lang_code in v.keys():
                entry.text = v[lang_code].decode('utf-8')
              else:
                entry.text = "UNDEFINED"
          else:
            # Iterate through all available language codes
            for lang_code, lang_name in sorted(v.iteritems()):
              if lang_code in english_pairs.keys():
                comment = ElementTree.Comment(' ' + lang_code + ' - ' + english_pairs[lang_code].decode('utf-8') + ' ')
              else:
                comment = ElementTree.Comment(' ' + lang_code + ' ')
              child.append(comment)
              entry = SubElement(child, 'item')
              entry.text = lang_name.decode('utf-8')
          f.write(self.prettify(top))
开发者ID:BABZAA,项目名称:language-list,代码行数:62,代码来源:Exporter.py

示例8: _dict_to_xml

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
    def _dict_to_xml(self):

        self._process_neighbor()

        bgp_xml = Element('bgp')

        as_xml = SubElement(bgp_xml, 'as-name')
        as_xml.text = self.asn['name']
        neighbor_xml = SubElement(bgp_xml, 'neighbor')

        # Walk the OrderedDict neighbor in Reversed Order to generate XML with
        # remote_ip in first position and remote_as in second position.
        for field in reversed(self.neighbor):

            if isinstance(map_fields.get(field), basestring):

                child_xml = SubElement(neighbor_xml, map_fields[field])
                child_xml.text = self._to_str(self.neighbor[field])

            elif isinstance(map_fields.get(field), dict):

                for child in map_fields[field]:

                    child_xml = self._create_or_get_element(neighbor_xml,
                                                            child)

                    child_of_child_xml = SubElement(child_xml,
                                                    map_fields[field][child])
                    child_of_child_xml.text = self._to_str(self.neighbor[field])

        return tostring(bgp_xml)
开发者ID:globocom,项目名称:GloboNetworkAPI,代码行数:33,代码来源:Generic.py

示例9: addSoftKey

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
 def addSoftKey(self,index,label,uri):
     softKey = SubElement(self.root, "SoftKey")
     softKey.set("index",index)
     label_key = SubElement(softKey,"Label")
     label_key.text = label
     uri_key = SubElement(softKey,"URI")
     uri_key.text = uri
开发者ID:macntouch,项目名称:visiblenumbers,代码行数:9,代码来源:Base.py

示例10: to_xml

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
    def to_xml(self):
        '''write file:
        tree.write("output.xml",encoding="ISO-8859-1", method="xml")
        '''
        survey = Element('survey')
        title = SubElement(survey,'title')
        title.text = self.title

        description = SubElement(survey,'description')
        description.text = self.description
        
        # startDate = SubElement(survey,'startDate')
        # startDate.text = str(self.startDate)

        # endDate = SubElement(survey,'endDate')
        # endDate.text = str(self.endDate)

        maxNumberRespondents = SubElement(survey,'maxNumberRespondents')
        maxNumberRespondents.text = str(self.maxNumberRespondents)

        duration = SubElement(survey,'duration')
        duration.text = str(self.duration)

        for consent in self.consents:
            survey.append(consent.to_xml())

        for section in self.sections:
            survey.append(section.to_xml())

        tree = ET.ElementTree(survey)

        return tree
开发者ID:nukru,项目名称:Swarm-Surveys,代码行数:34,代码来源:models.py

示例11: __init__

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
    def __init__(self, id, route, chunk):
        ((rfrom, rdest),) = route
        chunk, (cnum, maxc, fname, totalbsize) = chunk

        cont = Element('content')
        idtag = SubElement(cont, 'id')
        idtag.text = id

        rattrs = {
            'from': rfrom,
            'to': rdest,
        }
        routetag = SubElement(cont, 'route', rattrs)

        cattrs = {
            'number': cnum,
            'maxchunk': maxc,
            'filename': fname,
            'totalbsize': totalbsize,
        }
        chunktag = SubElement(cont, 'chunk', cattrs)
        chunktag.text = chunk

        props = {
            'type': 'file_chunk',
        }
        MMessage.__init__(self, TYPE, cont, props)
开发者ID:btrzcinski,项目名称:netchat,代码行数:29,代码来源:filetransfer.py

示例12: get_rgba_band

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def get_rgba_band(tmplt_band, tmplt_source, colours, levels, band_index):
    """Reclass to RGBA by a LUT (Look-Up Table)."""
    band = deepcopy(tmplt_band)
    source = deepcopy(tmplt_source)

    band.set('band', str(band_index + 1))

    colour_interp = SubElement(band, 'ColorInterp')
    colour_interp.text = COLOUR_BAND_INTERP[band_index]

    LUT = SubElement(source, 'LUT')
    reduction = 1 - 1.0e-6  # factor to reduce limit by a minimal number
    LUT.text = '%.6e:%i' % (levels[0] * reduction, colours[0][band_index])
    for i in range(len(levels) - 1):
        LUT.text += ',%.6e:%i' % (
            levels[i],
            colours[i + 1][band_index]
        )
        LUT.text += ',%.6e:%i' % (
            levels[i + 1] * reduction,
            colours[i + 1][band_index]
        )
    LUT.text += ',%.6e:%i' % (levels[-1], colours[-1][band_index])
    band.append(source)
    return band
开发者ID:SMHI-Apl,项目名称:Airviro-tools,代码行数:27,代码来源:res2png.py

示例13: addAddressXML

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
    def addAddressXML(self, root, serverInfo):
        #adds the address XML with the source server information
        #to the root XML tree. Input server information is a dict with
        #following keys: "mhsid",'host','port','protocol','site'
        # Returns element for address (in case additional info is required)
        addressE = SubElement(root, 'address')
        mhsidE = SubElement(addressE, 'mhsid')
        mhsidE.text = serverInfo.get('mhsid', "?")
        serverE = SubElement(addressE, 'server')
        serverE.text = serverInfo.get('host', "?")
        portE = SubElement(addressE, 'port')
        portE.text = str(serverInfo.get('port', "?"))
        protocolE = SubElement(addressE, 'protocol')
        protocolE.text = str(serverInfo.get('protocol', "?"))
        siteE = SubElement(addressE, 'site')
        siteE.text = serverInfo.get('site', "?")

        #optional components "location" "area" "welist"
        if serverInfo.has_key('domain') and serverInfo['domain'] is not None:
            d = serverInfo['domain']
            locationE = SubElement(addressE, 'location', proj=d['proj'],
              origx=str(d['origx']), origy=str(d['origy']),
              extx=str(d['extx']), exty=str(d['exty']))
        if serverInfo.has_key('area') and serverInfo['area'] is not None:
            d = serverInfo['area']
            areaE = SubElement(addressE, 'area', xdim=str(d['xdim']),
              ydim=str(d['ydim']))
        if serverInfo.has_key('parms') and serverInfo['parms'] is not None:
            parms = serverInfo['parms']
            self.addWelistXML(addressE, parms)

        return addressE
开发者ID:KeithLatteri,项目名称:awips2,代码行数:34,代码来源:IrtAccess.py

示例14: to_xml

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
    def to_xml(self):
        item = Element('item')

        item.set('uid', self.uid)

        if self.valid:
            item.set('valid', 'yes')
        else:
            item.set('valid', 'no')

        if self.autocomplete:
            item.set('autocomplete', self.autocomplete)

        if self.arg is not None:
            item.set('arg', self.arg)

        title = SubElement(item, 'title')
        title.text = self.title

        if self.subtitle is not None:
            subtitle = SubElement(item, 'subtitle')
            subtitle.text = self.subtitle

        if self.icon is not None:
            icon = SubElement(item, 'icon')

            if isinstance(self.icon, dict):
                icon.set('type', self.icon['type'])
                icon.text = self.icon['path']
            else:
                icon.text = self.icon

        return tostring(item)
开发者ID:owenwater,项目名称:jcalfred,代码行数:35,代码来源:alfred.py

示例15: _build_vcenter

# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import text [as 别名]
def _build_vcenter(vcenter_info):
    """
    <VC xmlns="http://www.vmware.com/UM">
        <hostname>10.255.79.5</hostname>
        <username>root</username>
        <password>vmware</password>
        <monitor>true</monitor>
    </VC>

    :param vcenter_info:
    :return:
    """
    attribs = {
        'xmlns': 'http://www.vmware.com/UM'
    }
    root = Element('vcServer', attribs)
    host = SubElement(root, 'hostname')
    host.text = str(vcenter_info['hostname'])
    username = SubElement(root, 'username')
    username.text = str(vcenter_info['username'])
    password = SubElement(root, 'password')
    password.text = str(vcenter_info['password'])
    monitor = SubElement(root, 'monitor')
    monitor.text = str(vcenter_info['monitor'])
    return tostring(root)
开发者ID:gitter-badger,项目名称:thunderhead,代码行数:27,代码来源:vcenter.py


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