本文整理汇总了Python中lxml.etree.Element方法的典型用法代码示例。如果您正苦于以下问题:Python etree.Element方法的具体用法?Python etree.Element怎么用?Python etree.Element使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lxml.etree
的用法示例。
在下文中一共展示了etree.Element方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: search
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def search(username, query):
"""
Search query text in user modules
Args:
username: Request username
query: Search String
Returns: An XML object with result XPATHs
"""
logging.debug('Searching query %s in user (%s) modules' % (query, username))
response = ET.Element('result')
modulenames = ModuleAdmin.get_modulelist(username)
for module in modulenames:
result = search_module(username, module, query)
for xpath in result:
path = ET.Element('path')
path.set('module', module)
path.text = xpath
response.append(path)
return True, response
示例2: get_capability
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def get_capability(self):
""" Returns device capabilities """
logging.debug('get_capability ..')
reply = ET.Element('reply')
if not self.connect():
reply.text = 'NetConf Session could not be established {%s}' % str(self)
return reply
self.disconnect()
if self.handle.server_capabilities:
caps = sorted(self.handle.server_capabilities)
reply.text = '\n'.join((c for c in caps if c.startswith('urn:ietf:params:netconf:')))
reply.text += '\n\n'
reply.text += '\n'.join((c for c in caps if not c.startswith('urn:ietf:params:netconf:')))
logging.info('Received device capabilities ..')
return reply
示例3: list
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def list():
""" get list of all collection entries """
cols_elem = ET.Element('collections')
for col in Col.objects.all():
path = os.path.join('data', 'collections', col.name)
if not os.path.exists(path):
logging.error('Collection has inconstancy : %s !!' % col.name)
continue
files = glob.glob(os.path.join(path, '*'))
for _file in files:
payload = ET.parse(_file)
for child in payload.getroot():
if child.tag == 'metadata':
cols_elem.append(child)
return cols_elem
示例4: run_restconf
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def run_restconf(username, device, msg):
""" Execute Restconf request """
session = RestClient(device)
if session is None:
reply = ET.Element('reply')
reply.text = 'Could not create session for %s' % protocol
return reply
if isinstance(msg, str):
msg = json.loads(msg)
url = 'http://' + device['host'] + ':' + str(device['port'])
if msg is None or msg == '':
return session.get_capability(url)
msg['url'] = url + msg['url']
return session.run(msg)
示例5: get_modules
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def get_modules(username):
"""
Return list of modules available to user + subscribed
"""
logger.debug("ModuleAdmin.get_modules: enter")
modules = ET.Element('modulelist')
user = User.objects.filter(username=username)
mlist = list()
for _file in glob.glob(os.path.join(ServerSettings.yang_path(username), '*.yang')):
mlist.append(os.path.basename(_file))
mlist.sort()
for fname in mlist:
module = ET.Element('module')
module.text = os.path.basename(fname)
name = module.text.split('.yang')[0]
if UserProfile.objects.filter(user=user, module=name).exists():
module.set('subscribed', 'true')
modules.append(module)
logger.info("ModuleAdmin.get_modules: returning (%d) modules .. exit" % len(modules))
return modules
示例6: _build_proto
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def _build_proto(proto, addr, port, uname, pwd):
""" Build one proto xml instance """
transport = ET.Element('transport')
transport.set('type', proto)
elem = ET.Element('address')
elem.text = addr
transport.append(elem)
elem = ET.Element('port')
elem.text = port
transport.append(elem)
elem = ET.Element('username')
elem.text = uname
transport.append(elem)
elem = ET.Element('password')
elem.text = pwd
transport.append(elem)
return transport
示例7: profile_handler
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def profile_handler(request):
""" HTTP request handler for profile request """
profiles = ET.Element('profiles')
if request.user.is_authenticated():
uid = request.user.id
logging.debug("User Authenticated (%s)" % request.user.username)
entries = DeviceProfile.objects.filter(Q(user=uid) | Q(shared=True))
for e in entries:
profile = _build_device_profile(e)
profiles.append(profile)
entries = Collection.objects.all()
for e in entries:
profile = _build_collection_profile(e)
profiles.append(profile)
return HttpResponse(Response.success('profile', 'ok', xml=profiles))
示例8: parse_search
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def parse_search(response: Response) -> SearchResult:
try:
elem = parse_xml(response)
except RetsApiError as e:
if e.reply_code == 20201: # No records found
return SearchResult(0, False, ())
raise
count_elem = elem.find('COUNT')
if count_elem is not None:
count = int(count_elem.get('Records'))
else:
count = None
try:
data = tuple(_parse_data(elem))
except RetsParseError:
data = None
return SearchResult(
count=count,
# python xml.etree.ElementTree.Element objects are always considered false-y
max_rows=elem.find('MAXROWS') is not None,
data=data,
)
示例9: delete_to_prj
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [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
示例10: _render_response
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [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
示例11: buildXMLNodes
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def buildXMLNodes(self, element, node):
if type(node) is str or type(node) is int or type(node) is bool:
node = str(node)
element.text = XML.CDATA(node)
else:
for k, v in node.iteritems():
if type(v) is dict:
# serialize the child dictionary
child = XML.Element(k)
self.buildXMLNodes(child, v)
element.append(child)
elif type(v) is list:
if k[-1] == 's':
name = k[:-1]
else:
name = k
for item in v:
child = XML.Element(name)
self.buildXMLNodes(child, item)
element.append(child)
else:
# add attributes to the current element
element.set(k, unicode(v))
示例12: __init__
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def __init__(self, keep_urls=False, force_studio_format=False, skip_hidden=False, keep_studio_urls=False):
'''
if keep_urls=True then the original url_name attributes are kept upon import and export,
if nonrandom (ie non-Studio).
if keep_studio_urls=True and keep_urls=True, then keep random urls.
'''
self.course = etree.Element('course')
self.metadata = etree.Element('metadata')
self.urlnames = []
self.xml = None # only used if XML xbundle file was read in
self.keep_urls = keep_urls
self.force_studio_format = force_studio_format # sequential must be followed by vertical in export
self.skip_hidden = skip_hidden
self.keep_studio_urls = keep_studio_urls
return
#----------------------------------------
# creation by parts
示例13: import_metadata_from_directory
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def import_metadata_from_directory(self, dir):
# load policies
# print "ppath = ", (path(dir) / 'policies/*')
for pdir in glob.glob(path(dir) / 'policies/*'):
# print "pdir=",pdir
policies = etree.Element('policies')
policies.set('semester',os.path.basename(pdir))
for fn in glob.glob(path(pdir) / '*.json'):
x = etree.SubElement(policies,os.path.basename(fn).replace('_','').replace('.json',''))
x.text = open(fn).read()
self.add_policies(policies)
# load about files
for afn in glob.glob(dir / 'about/*'):
try:
self.add_about_file(os.path.basename(afn), open(afn).read())
except Exception as err:
print "Oops, failed to add file %s, error=%s" % (afn, err)
示例14: export_to_directory
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def export_to_directory(self, exdir='./'):
'''
Export xbundle to edX xml directory
First insert all the intermediate descriptors needed.
Do about and XML separately.
'''
coursex = etree.Element('course')
semester = self.course.get('semester')
coursex.set('url_name',semester)
coursex.set('org',self.course.get('org'))
coursex.set('course',self.course.get('course'))
self.export = self.make_descriptor(self.course, semester)
self.export.append(self.course)
self.add_descriptors(self.course)
# print self.pp_xml(self.export)
self.dir = self.mkdir(path(exdir) / self.course_id())
self.export_meta_to_directory()
self.export_xml_to_directory(self.export[0])
# write out top-level course.xml
open(self.dir/'course.xml','w').write(self.pp_xml(coursex))
示例15: add_descriptors
# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import Element [as 别名]
def add_descriptors(self, xml, parent=''):
'''
Recursively walk through self.course and add descriptors
A descriptor is an intermediate tag, which points to content
via a url_name. These are used by edX to simplify loading
of course content.
'''
for elem in xml:
if self.force_studio_format:
if xml.tag=='sequential' and not elem.tag=='vertical': # studio needs seq -> vert -> other
# move child into vertical
vert = etree.Element('vertical')
elem.addprevious(vert)
vert.append(elem)
elem = vert # continue processing on the vertical
if elem.tag in self.DescriptorTags and not elem.get('url_name',''):
desc = self.make_descriptor(elem, parent=parent)
elem.addprevious(desc)
desc.append(elem) # move descriptor to become new parent of elem
self.add_descriptors(elem, desc.get('url_name')) # recurse
#-----------------------------------------------------------------------------
# tests